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.
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
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With