MrDatabase
MrDatabase

Reputation: 44505

How can I programmatically determine if I have write privileges using C# in .Net?

How can I determine if I have write permission on a remote machine in my intranet using C# in .Net?

Upvotes: 5

Views: 9017

Answers (4)

Treb
Treb

Reputation: 20299

Been there too, the best and most reliable solution I found was this:

bool hasWriteAccess = true;
string remoteFileName = "\\server\share\file.name"

try
{
    createRemoteFile(remoteFileName);   
}
catch (SystemSecurityException)
{
     hasWriteAccess = false;   
}

if (File.Exists(remoteFileName))
{
    File.Delete(remoteFileName);
}

return hasWriteAccess;

Upvotes: 4

Dr8k
Dr8k

Reputation: 1096

ScottKoon is write about checking the windows ACL permissions. You can also check the managed code permissions using CAS (Code Access Security). This is a .Net specific method of restricting permissions. Note, if the user doesn't have write permissions then the code will never have write permissions (even if CAS says it does) - the most restrictive permissions between the two win.

CAS is pretty easy to use - you can even add declarative attributes you the start of your methods. You can read more at MSDN

Upvotes: 1

ScottKoon
ScottKoon

Reputation: 3493

Check out this forum post.

http://bytes.com/forum/thread389514.html

It describes using the objects in the System.Security.AccessControl namespace to get a list of the ACL permissions for a file. It's only available in .NET 2.0 and higher. I think it also assumes that you have an SMB network. I'm not sure what it would do if you were using a non-Windows network.

If you aren't on .NET 2.0 or higher, it's the usual pInvoke and Win32 API jazz.

Upvotes: 3

Rob Walker
Rob Walker

Reputation: 47502

The simple answer would be to try it and see. The Windows security APIs are not for the faint of heart, and may be possible you have write permission without having permission to view the permissions!

Upvotes: 6

Related Questions