Delphi set to read only files from folder and subfolders

↘锁芯ラ 提交于 2019-12-08 05:26:23

问题


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

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