2011-04-05 83 views
1

有没有办法,我可以删除属性“只读”?删除从文件夹,其子文件夹和其中的所有文件只读

我想这:

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

但它不会做的工作

+1

我看到你的代码与这个接受的答案中的代码类似,但根据该帖子,答案似乎已经奏效。您是否尝试了该链接上的其他建议? http://stackoverflow.com/questions/2316308/remove-readonly-of-folder-from-c – 2011-04-05 03:04:58

回答

7

几乎尝试:

var di = new DirectoryInfo("C:\\Work"); 

foreach (var file in di.GetFiles("*", SearchOption.AllDirectories)) 
    file.Attributes &= ~FileAttributes.ReadOnly; 
0

这是我发现谷歌搜索。

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

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

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; 
} 

我跑进想要清除的目录和任何子文件/目录,它可能是读/写标志的这个samiliar问题。使用foreach循环听起来像额外的工作,当Attrib命令行功能工作得很好,几乎是瞬间的。

+0

我喜欢这种方法,虽然它不是便携式。 – CJBrew 2017-03-31 13:02:37

相关问题