Delphi设置为仅读取文件夹和子文件夹中的文件 [英] Delphi set to read only files from folder and subfolders

查看:161
本文介绍了Delphi设置为仅读取文件夹和子文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将特定文件夹和子文件夹中的文件放在delphi中只读?
我知道我可以将FileSetAttr的文件夹放在只读状态,但是有没有办法将文件夹和子文件夹中的文件放入?

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 ?

谢谢

推荐答案

您需要遍历目录中的所有文件,并递归遍历所有子目录。您可以使用此函数来做到这一点:

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;

然后您将其放在一起:

EnumerateFiles('C:\MyDir', MakeReadOnly);

这篇关于Delphi设置为仅读取文件夹和子文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆