How to check if String Path is a “file” or “directory” if the path does not exist?

I have a function that automatically creates the specified Path , determining whether the String Path 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 is not? How to check if a String Path File or Directory if it does not exist?

+5
source share
1 answer

If the files in your script must have extensions, you can use this method.

NOTE. . On Windows, it is allowed to have periods in directories, but this was mainly introduced for file compatibility with the cross operating system. In strict Windows environments, it is considered bad form to have files without extensions or to place periods or spaces in directory names. If you do not need to consider this scenario, you can use this method. If not, you will have to have some kind of flag sent through a chain or 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 parse the file type, you can do this simply:

 if(System.IO.Path.HasExtension(strPath)) { //It is a file } 
+5
source

Source: https://habr.com/ru/post/1203141/


All Articles