Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a String Path is a 'File' or 'Directory' if path doesn't exist?

Tags:

c#

io

I have a function that automatically creates a specified Path by determining whether the String Path is a File or Directory.

Normally, i would use this if the path already exists:

FileAttributes attributes = File.GetAttributes("//Path");

if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
    {
        Directory.CreateDirectory("//Path");
    }

But what if it doesn't? How to check whether the String Path is a File or Directory if it doesn't exist?

like image 672
Enumy Avatar asked Sep 22 '14 13:09

Enumy


People also ask

How do you check if a string is a directory?

To check if a string represents a path or a file programatically, you should use API methods such as isFile(), isDirectory().

How do you check if a folder exists and if not create it?

You can use os. path. exists('<folder_path>') to check folder exists or not.

How do you check if it is a file or directory in Java?

To test to see if a file or directory exists, use the exists method of the Java File class, as shown in this example: File tmpDir = new File("/var/tmp"); boolean exists = tmpDir. exists(); The existing method of the Java File class returns true if the file or directory exists, and false otherwise.


1 Answers

If files in your scenario must have extensions then you could use this method.

NOTE: It is legal in windows to have periods in directories, but this was mostly introduced for cross operating system compatibility of files. In strictly windows environments it is considered bad form to have files without extensions or to put periods or spaces in directory names. If you do not need to account for that scenario then you could use this method. If not you would have to have some sort of flag sent through the chain or a structure to identify the intent of the string.

var ext = System.IO.Path.GetExtension(strPath);
if(ext == String.Empty)
{
    //Its a path
}

If you do not need to do any analysis on file type you can go as simple as:

if(System.IO.Path.HasExtension(strPath))
{
    //It is a file
}
like image 166
Carter Avatar answered Oct 06 '22 13:10

Carter