问题
How can I put the files from a specific folder and subfolders to read only in delphi? I know that I can put the folder with FileSetAttr to read only but is there a way to put the files from the folder and subfolders ?
Thanks
回答1:
You need to iterate over all the files in a directory, and recursively over all the sub-directories. You can use this function to do that:
type
TFileEnumerationCallback = procedure(const Name: string);
procedure EnumerateFiles(const Name: string;
const Callback: TFileEnumerationCallback);
var
F: TSearchRec;
begin
if FindFirst(Name + '\*', faAnyFile, F) = 0 then begin
try
repeat
if (F.Attr and faDirectory <> 0) then begin
if (F.Name <> '.') and (F.Name <> '..') then begin
EnumerateFiles(Name + '\' + F.Name, Callback);
end;
end else begin
Callback(Name + '\' + F.Name);
end;
until FindNext(F) <> 0;
finally
FindClose(F);
end;
end;
end;
This is a general purpose routine. You can supply a callback procedure that will be called with the name of each file. Inside that callback procedure do what ever you want.
Your callback procedure would look like this:
procedure MakeReadOnly(const Name: string);
begin
FileSetAttr(Name, FileGetAttr(Name) or faReadOnly);
end;
And you'd put it together like this:
EnumerateFiles('C:\MyDir', MakeReadOnly);
来源:https://stackoverflow.com/questions/21816067/delphi-set-to-read-only-files-from-folder-and-subfolders