这是尝试将文件名添加到字符串列表。如果将重复的文件名添加到列表中 引发异常并从列表中删除原始文件。我从帮助文件中了解到,如果找到重复文件,将返回现有条目的索引,然后可以使用该索引删除现有条目。
此代码的问题在于,当找到重复项时,不会执行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;
答案 0 :(得分:5)
引发的错误是EStringListError
。您正在寻找EListError
。
答案 1 :(得分:3)
检测到重复条目时,dupError
会引发EStringListError
异常。现有项的索引在错误消息中指定,但不会以其他方式公开。因此,您必须解析错误消息以发现索引,或者停止使用dupError
并使用IndexOf()
代替:
{ 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;