如何使用c#更改文件夹中每个文件的只读文件属性?

时间:2022-09-11 17:00:43

How do I change the Read-only file attribute for each file in a folder using c#?

如何使用c#更改文件夹中每个文件的只读文件属性?

Thanks

4 个解决方案

#1


13  

foreach (string fileName in System.IO.Directory.GetFiles(path))
{
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);

    fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
    // or
    fileInfo.IsReadOnly = true;
}

#2


9  

You can try this : iterate on each file and subdirectory :

你可以试试这个:迭代每个文件和子目录:

public void Recurse(DirectoryInfo directory)
{
    foreach (FileInfo fi in directory.GetFiles())
    {
        fi.IsReadOnly = false; // or true
    }

    foreach (DirectoryInfo subdir in directory.GetDirectories())
    {
        Recurse(subdir);
    }
}

#3


2  

Use File.SetAttributes in a loop iterating over Directory.GetFiles

在遍历Directory.GetFiles的循环中使用File.SetAttributes

#4


1  

If you wanted to remove the readonly attributes using pattern matching (e.g. all files in the folder with a .txt extension) you could try something like this:

如果您想使用模式匹配删除readonly属性(例如,扩展名为.txt的文件夹中的所有文件),您可以尝试这样的方法:

Directory.EnumerateFiles(path, "*.txt").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);

#1


13  

foreach (string fileName in System.IO.Directory.GetFiles(path))
{
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);

    fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
    // or
    fileInfo.IsReadOnly = true;
}

#2


9  

You can try this : iterate on each file and subdirectory :

你可以试试这个:迭代每个文件和子目录:

public void Recurse(DirectoryInfo directory)
{
    foreach (FileInfo fi in directory.GetFiles())
    {
        fi.IsReadOnly = false; // or true
    }

    foreach (DirectoryInfo subdir in directory.GetDirectories())
    {
        Recurse(subdir);
    }
}

#3


2  

Use File.SetAttributes in a loop iterating over Directory.GetFiles

在遍历Directory.GetFiles的循环中使用File.SetAttributes

#4


1  

If you wanted to remove the readonly attributes using pattern matching (e.g. all files in the folder with a .txt extension) you could try something like this:

如果您想使用模式匹配删除readonly属性(例如,扩展名为.txt的文件夹中的所有文件),您可以尝试这样的方法:

Directory.EnumerateFiles(path, "*.txt").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);