2

is there a way that i can remove the property "read only"?

i tried this:

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

but it does not do the job

jeremychan
  • 4,309
  • 10
  • 42
  • 56
  • 1
    I see that your code is similar to the one in this accepted answer but according to that post, the answer seems to have worked. Have you tried the other suggestions on that link? http://stackoverflow.com/questions/2316308/remove-readonly-of-folder-from-c – Mamta D Apr 05 '11 at 03:04

3 Answers3

9

Almost, try:

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

foreach (var file in di.GetFiles("*", SearchOption.AllDirectories)) 
    file.Attributes &= ~FileAttributes.ReadOnly;
John Rasch
  • 62,489
  • 19
  • 106
  • 139
1

A better way of doing might be.

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

I ran into this samiliar problem of wanting to clear the read/write flag of a directory and any sub-files/directories it might have. And using a foreach loop sound like extra work, when the Attrib command line function works just fine and is almost instantaneous.

nagates
  • 620
  • 13
  • 40
0

This is what I found with a google search.

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

Obviously this is for only one file so you will have to loop over the files and set the attributes for each.