Question

Till now all cases I met was like:

  • try to store file
  • if file is stored that's fine
  • if file can not be stored tell about it (no path, no permission, etc)

Currently I am standing before problem how to check if file can be stored without storing it. In general I don't even know what to ask Google, because all returned results I got are about permissions, and general in Linux, and I need it under C#/Windows.

How such checking can be done?

Was it helpful?

Solution

Since you don't want to attempt writing to the folder, you could consider this approach.

You can put a try catch around this:

System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);

i.e.

public bool CanWriteToPath(string folderPath) 
{
    try 
    { 
        var ds = Directory.GetAccessControl(folderPath);
        return true;
    } catch (UnauthorizedAccessException)
    {
        return false;
    }
}

It will only succeed if you have permissions.

Sorry that it still has to use a try/catch.

OTHER TIPS

How about use try catch block? If any exception occurs - you can catch it and determine than can not save file. If no exception occurs, file successfully saved.

There is a Directory.GetAccessControl method and File.GetAccessControl method in File.IO namespace.

If you want to know the status before actually writing the file, check if the specified directory has write permissions for the user. If all is well, write the file. You could also use a try catch block as suggested in other answers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top