【问题标题】:removing readonly from folder, its sub folders and all the files in it从文件夹、其子文件夹和其中的所有文件中删除只读
【发布时间】:2011-07-29 15:16:38
【问题描述】:

有没有办法可以删除“只读”属性?

我试过这个:

var di = new DirectoryInfo("C:\\Work");
                di.Attributes &= ~FileAttributes.ReadOnly;

但它没有做这项工作

【问题讨论】:

  • 我看到您的代码与此已接受答案中的代码相似,但根据该帖子,答案似乎有效。您是否尝试过该链接上的其他建议? stackoverflow.com/questions/2316308/…

标签: c# wpf


【解决方案1】:

可能是更好的做法。

string cmd = string.Format(" /C ATTRIB -R  \"{0}\\*.*\" /S /D", binPath);
CallCommandlineApp("cmd.exe", cmd);

private static bool CallCommandlineApp(string progPath, string arguments)
{
   var info = new ProcessStartInfo()
    {
        UseShellExecute = false,
        RedirectStandardOutput = true,
        FileName = progPath,
        Arguments = arguments

    };

    var proc = new Process()
    {
        StartInfo = info
    };
    proc.Start();

    using (StreamReader stReader = proc.StandardOutput)
    {
        string output = stReader.ReadToEnd();
        Console.WriteLine(output);

    }

    // TODO: Do something with standard error. 
    proc.WaitForExit();
    return (proc.ExitCode == 0) ? true : false;
}

我遇到了想要清除目录的读/写标志以及它可能具有的任何子文件/目录的类似问题。并且使用 foreach 循环听起来像是额外的工作,而 Attrib 命令行功能工作得很好并且几乎是瞬时的。

【讨论】:

  • 我喜欢这种方法,虽然它不那么便携。
【解决方案2】:

这是我通过谷歌搜索找到的。

File.SetAttributes(filePath, File.GetAttributes(filePath) & ~(FileAttributes.ReadOnly));

显然这仅适用于一个文件,因此您必须遍历文件并为每个文件设置属性。

【讨论】:

    【解决方案3】:

    差不多,试试:

    var di = new DirectoryInfo("C:\\Work");
    
    foreach (var file in di.GetFiles("*", SearchOption.AllDirectories)) 
        file.Attributes &= ~FileAttributes.ReadOnly;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2019-02-16
      • 1970-01-01
      • 2012-07-21
      相关资源
      最近更新 更多