2014-10-24 1 views
-2

이것은 문자열 목록에 파일 이름을 추가하려는 시도입니다. 중복 파일 이름이 목록에 추가 된 경우 예외가 발생하고 목록에서 원본 파일이 제거됩니다. 도움말 파일에서 중복 파일이 발견되면 기존 항목의 색인이 반환되어 기존 항목을 삭제할 수 있다는 것을 알고 있습니다.dupError를 사용하여 StringList에서 중복을 처리하는 방법

이 코드의 문제점은 중복이 발견되면 EListError Exception의 코드가 실행되지 않는다는 것입니다.

내 질문은 중복 파일 이름이있는 경우 어떻게 원래 파일 이름을 목록에서 삭제합니까? 본질적으로 그것이 추가 될 때 중복이 발견되면 목록에서 원본 파일을 제거하고 싶습니다. 불행히도 예외 트랩의 코드는 중복 파일이 목록에 추가 될 때 실행되지 않습니다.

{ Create a list of files to delete } 
iListOfImagesToDelete := TStringList.Create; 
try 
    { Get a ListOfFiles in each collection } 
    iCollectionList := TStringList.Create; 
    try 
    iListOfImagesToDelete.Duplicates := dupError; 
    iListOfImagesToDelete.Sorted := True; 
    { Add filenames to a stringlist with Duplicates set to dupError and Sorted set to True } 
    iFileCount := iCollectionList.Count; 
    for j := 0 to iFileCount - 1 do 
     begin 
     iFilename := iCollectionList[j]; 
     if FileExists(iFilename) then 
     begin 
      try 
      iFileIndex := iListOfImagesToDelete.Add(iFilename); 
      except 
      { file exists in the list } 
      on EListError do 
      begin 
       ShowMessage(ExtractFilename(ifilename) + ' exists.'); 
       { Remove the original duplicate file from the list } 
       iListOfImagesToDelete.Delete(iFileIndex); 
      end; 
     end; 
     end; 
    end; 
    finally 
    iCollectionList.Free; 
    end; 
finally 
    iListOfImagesToDelete.Free; 
    end; 

답변

3

중복 항목이 감지되면 dupErrorEStringListError 예외를 발생시킵니다. 기존 항목의 색인은 오류 메시지에 지정되어 있지만 달리 노출되지는 않습니다. 그래서 대신 IndexOf()를 인덱스를 발견, 또는 dupError 사용을 중지하고 사용하는 오류 메시지를 구문 분석하는 중 것이다 :

{ Create a list of files to delete } 
iListOfImagesToDelete := TStringList.Create; 
try 
    { Get a ListOfFiles in each collection } 
    iCollectionList := TStringList.Create; 
    try 
    iListOfImagesToDelete.Sorted := True; 
    { Add filenames to a stringlist } 
    iFileCount := iCollectionList.Count; 
    for j := 0 to iFileCount - 1 do 
    begin 
     iFilename := iCollectionList[j]; 
     if FileExists(iFilename) then 
     begin 
     iFileIndex := iListOfImagesToDelete.IndexOf(iFilename); 
     if iFileIndex = -1 then 
     begin 
      { file does not exist in the list } 
      iListOfImagesToDelete.Add(iFilename); 
     end else 
     begin 
      { file exists in the list } 
      ShowMessage(ExtractFileName(iFilename) + ' exists.'); 
      { Remove the original duplicate file from the list } 
      iListOfImagesToDelete.Delete(iFileIndex); 
     end; 
     end; 
    end; 
    finally 
    iCollectionList.Free; 
    end; 
finally 
    iListOfImagesToDelete.Free; 
end; 
5

오류 발생시는 EStringListError입니다. EListError을 찾고 있습니다.

+0

감사 우베 ...하지만 지금은 iFileIndex = iListOfImagesToDelete.Add (iFilename); 0을 반환해야 할 때 1을 반환합니다. 어떤 아이디어입니까? – Bill