ReadOnly folder?

G

Guest

I'm trying to write a function that determines whether a directory can be written to, short of trying to create a file and catching the exception, is there any fancier way of doing it?

I tried having a look at the FileIOPermission class in System.Security.Permissions, but it didn't seem to do it....am I doing it wrong? Show me!

static bool WritableDirectory(string dir)
{
if(!Directory.Exists(dir)) return false;
try
{
FileIOPermission fp = new FileIOPermission(
FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, dir);
return ((fp.AllFiles & FileIOPermissionAccess.Write) != 0);
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}

}


Cheers!
 
N

Nicholas Paldino [.NET/C# MVP]

Patty,

Use the DirectoryInfo class, instantiating an instance for the directory
in question. Then check to see if the Attributes property on the instance
has the value of FileAttributes.ReadOnly in it. If it does, then it is read
only, otherwise, it is not.

Of course, even if the directory is not read only, you might not have
access to it from your code. In this case, you would create an instance of
the FileIOPermissions class, with the directory and the access level you
want. Then, call Demand. If a SecurityException is thrown, then you know
you won't be able to write to it.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Patty O'Dors said:
I'm trying to write a function that determines whether a directory can be
written to, short of trying to create a file and catching the exception, is
there any fancier way of doing it?
I tried having a look at the FileIOPermission class in
System.Security.Permissions, but it didn't seem to do it....am I doing it
wrong? Show me!
 
A

Adam W Root

DirectoryInfo dir = new DirectoryInfo("c:\\");

if ((dir.Attributes & FileAttributes.ReadOnly) > 0)
MessageBox.Show("ReadOnly!");

Patty O'Dors said:
I'm trying to write a function that determines whether a directory can be
written to, short of trying to create a file and catching the exception, is
there any fancier way of doing it?
I tried having a look at the FileIOPermission class in
System.Security.Permissions, but it didn't seem to do it....am I doing it
wrong? Show me!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top