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 am looking for something like File.CanCreate(@"C:\myfolder\myfile.aaa" ), but have not found such a method. The only thing I thought was to try to create a dummy file and check for exceptions, but this is a solution that also affects performance. Do you know the best solution?

+6
source share
2 answers

In fact, creating a dummy file will not have much performance impact in most applications. Of course, if you have additional permissions to create, but not to destroy, you might get a little hairy ...

Guides are always convenient 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; } 
+14
source

You can use CAS to make sure that there are no .NET policies (caspol) restricting the creation and writing of a file at this location.

But this will not cover Windows policies. You will have to manually check the NTFS policies. And even then there are processes that may decide that you are not allowed to create the file (for example, an anti-virus scanner).

The best and most complete way is to try.

+1
source

All Articles