Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 801
Pablo Retyk Avatar asked Nov 25 '08 10:11

Pablo Retyk


People also ask

How do you check if a file exists in a specific folder?

exists() method in Python is used to check whether the specified path exists or not. This method can also be used to check whether the given path refers to an open file descriptor or not. Parameter: path: A path-like object representing a file system path.

Which of the following does not create a new file if the file is not found in the directory?

open() in Python does not create a file if it doesn't exist.

How check file exist in folder or not in C#?

Exists() Method in C# with Examples. File. Exists(String) is an inbuilt File class method that is used to determine whether the specified file exists or not. This method returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false.


1 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;
}
like image 108
Marc Gravell Avatar answered Sep 19 '22 07:09

Marc Gravell