If I have the right to create a new file in the program directory I want to create the file there, if not I want to create the file in the program's AppData folder.
views:
155answers:
2
+7
A:
You can use FileIOPermission to determine if your application has particular permissions for a file / folder.
From MSDN:
FileIOPermission f = new FileIOPermission(PermissionState.None);
f.AllLocalFiles = FileIOPermissionAccess.Read;
try
{
f.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
}
EDIT: A more explicit repsonse to your question could be something like :
private string GetWritableDirectory()
{
string currentDir = Environment.CurrentDirectory; // Get the current dir
FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, currentDir);
try
{
f.Demand(); // Check for write access
}
catch (SecurityException s)
{
return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) ; // Return the appdata (you may want to pick a differenct folder here)
}
return currentDir; // Have write access to current dir
}
PaulB
2009-04-15 10:31:42
weiqure doesn't say if he's using c# on Windows - but I didn't know this.
ChrisF
2009-04-15 10:36:34
True - but he is using .net
PaulB
2009-04-15 10:40:20
Do'h - it help if you read the tags.
ChrisF
2009-04-15 10:48:05
Yep. Deleted my Try-Catch answer
Dead account
2009-04-15 11:08:09
I don't really understand this. If I ran this code with my programme being in C:\Windows, wouldn't it complain?
2009-04-15 11:11:35
@weique - not if you had write rights to C:\Windows, which you would if you were logged in as an admin
ChrisF
2009-04-15 11:47:54
I am not logged in as an admin so I shouldn't have write rights to C:\Windows. I also tried it out on Windows 7 and I got the same result. All I'm doing is 'Console.WriteLine(GetWritableDirectory());'.
2009-04-15 12:13:59
You must have write access to c:\windows if you copied the executable in there?
PaulB
2009-04-15 13:56:43
I copied it there with another account.
2009-04-15 14:02:11
+1
A:
Just try to create the folder and catch the ensuing exception: everything else isn't safe because since Windows is (more or less) a real-time systen, between the moment where you test for the rights and the moment of folder creation, the rights might have been changed. Consider the following potential, critical event chain:
- User is about to change the folder rights
- Application tests for folder creation rights: test for rights successful
- User commits the changes
- Application tries to create the folder
Konrad Rudolph
2009-04-15 11:42:28
Please don't downvote without leaving a justfication. How should I know what in my posting was deemed wrong?
Konrad Rudolph
2009-04-15 12:09:32