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

前端 未结 4 1179
礼貌的吻别
礼貌的吻别 2021-02-14 18:11

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

Thanks

相关标签:
4条回答
  • 2021-02-14 18:28

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

    0 讨论(0)
  • 2021-02-14 18:47
    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;
    }
    
    0 讨论(0)
  • 2021-02-14 18:48

    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);
        }
    }
    
    0 讨论(0)
  • 2021-02-14 18:54

    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:

    Directory.EnumerateFiles(path, "*.txt").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);
    
    0 讨论(0)
提交回复
热议问题