Delphi function, Not allowing files and folders from main directory during compression

限于喜欢 提交于 2019-12-02 23:45:32

问题


I used this code to combined all files into one from a directory, not really compression,

procedure CompressDirectory(InDir : string; OutStream : TStream);
var
AE : TArchiveEntry;
procedure RecurseDirectory(ADir : string);
var
sr : TSearchRec;
TmpStream : TStream;
begin
if FindFirst(ADir + '*', faAnyFile, sr) = 0 then
begin
repeat
if (sr.Attr and (faDirectory or faVolumeID)) = 0 then
begin
// We have a file (as opposed to a directory or anything
// else). Write the file entry header.
AE.EntryType := aeFile;
AE.FileNameLen := Length(sr.Name);
AE.FileLength := sr.Size;
OutStream.Write(AE, SizeOf(AE));
OutStream.Write(sr.Name[1], Length(sr.Name));
// Write the file itself
TmpStream := TFileStream.Create(ADir + sr.Name, fmOpenRead or fmShareDenyWrite);
OutStream.CopyFrom(TmpStream, TmpStream.Size);
TmpStream.Free;
end;
if (sr.Attr and faDirectory) > 0 then
begin
if (sr.Name <> '.') and (sr.Name <> '..') then
begin
// Write the directory entry
AE.EntryType := aeDirectory;
AE.DirNameLen := Length(sr.Name);
OutStream.Write(AE, SizeOf(AE));
OutStream.Write(sr.Name[1], Length(sr.Name));
// Recurse into this directory
RecurseDirectory(IncludeTrailingPathDelimiter(ADir + sr.Name));
end;
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
// Show that we are done with this directory
AE.EntryType := aeEOD;
OutStream.Write(AE, SizeOf(AE));
end;
begin
RecurseDirectory(IncludeTrailingPathDelimiter(InDir));
end;

What if I want the compressDirectory function not to include some folders and files? What would be the CompressDirectory function code look like? please guide me, thanks.

> Edited, removed image for space.


回答1:


The code already employs a technique for skipping certain unwanted file names:

if (sr.Name <> '.') and (sr.Name <> '..') then

Simply use that same technique to exclude whatever other files you wish. You can hard-code the exclusion list into the code, as is already done with the . and .. names, or you can pass a list of names into the function as another parameter. Before you add a file to the archive, check whether that file name is in the list of files to exclude.

For example, if the list of excluded names were in a TStrings descendant, you might use something like this:

if ExcludedNames.IndexOf(sr.Name) >= 0 then
  Continue; // Skip the file because we've been told to exclude it.

You could enhance this to check the full path of the file instead of just the local name. You could also enhance it to support wildcards in the list of exclusions.



来源:https://stackoverflow.com/questions/17956122/delphi-function-not-allowing-files-and-folders-from-main-directory-during-compr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!