How to check if file can be stored in particular location without storing/creating file?

StackOverflow https://stackoverflow.com/questions/22653633

  •  21-06-2023
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top