How to check if I can create a file in a specific folder

I need to know if I can create a file in a specific folder, but there are too many things to check such as permissions, duplicate files, etc. I'm looking for something like File.CanCreate(@"C:\myfolder\myfile.aaa"), but haven't found such a method. The only thing I thought is to try to create a dummy file and check for exceptions but this is an ungly solution that also affects performance. Do you know a better solution?

Answers


In reality, creating a dummy file isn't going to have a huge performance impact in most applications. Of course, if you have advanced permissions with create but not destroy it might get a bit hairy...

Guids are always handy for random names (to avoid conflicts) - something like:

string file = Path.Combine(dir, Guid.NewGuid().ToString() + ".tmp");
// perhaps check File.Exists(file), but it would be a long-shot...
bool canCreate;
try
{
    using (File.Create(file)) { }
    File.Delete(file);
    canCreate = true;
}
catch
{
    canCreate = false;
}

You can use CAS to verify that there are no .NET policies (caspol) restricting the creating and writing of a file on that location.

But this will not cover the windows policies. You'll have to manually check the NTFS policies. And even then there are processes that can decide you're not allowed to create a file (for instance a virus scanner).

The best and most complete way is to try it.


Need Your Help

How to change the email language format based on locale?

ruby-on-rails delayed-job

I am having different locales for countries, i am able to translate words for others but how to translate it for mailers?

Indermediate sub-patch Node.js package version

node.js npm semantic-versioning

I'm providing accompanying package that matches the version of the main NPM package, already in major.minor.patch format (e.g. 1.3.1).