1

I have a class named FolderHelper with a method ReadOnly - the aim is to check whether the specified directory is read-only and return a bool true or false.

public static bool ReadOnly(string path)
{
    DirectoryInfo directoryInfo = new DirectoryInfo(path);

    if (directoryInfo.Attributes.HasFlag(FileAttributes.ReadOnly))
    {
        return true;
    }
    return false;
}

I have set the directory to read-only but the method always returns false - can anyone suggest any reasons why?

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
JoelH
  • 123
  • 1
  • 1
  • 6

2 Answers2

3

Readonly flag can be applied to files only, not to directories. If you will try to set this flag on directory using windows explorer - you'll end up with the same result - flag will not be set to the directory but can be set/unset to files it contains. Since flag can't be set to directory - obviously you can't get it from directory.

Probably you need to check write permissions on this directory in order to determine if user can create/modify files contained in this directory. You can use Directory.GetAccessControl to check it.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
0

Found this on another stackOverflow article and may be this is what you need to do

C# Test if user has write access to a folder

 public bool IsReadOnly(string dirPath)
    {
        try
        {
            using (FileStream fs = File.Create(
                Path.Combine(
                    dirPath, 
                    Path.GetRandomFileName()
                ), 
                1,
                FileOptions.DeleteOnClose)
            )
            { }
            return false;
        }
        catch
        {

                return true;
        }
    }
Community
  • 1
  • 1
Viru
  • 2,228
  • 2
  • 17
  • 28