User19280314
User19280314

Reputation: 3

How to get a file/folder type in C#?

I was thinking of making a more "advanced" version of System.IO.Path, System.IO.File & System.IO.Directory.

Obviously I started with System.IO.Path, because the base for File and Directory will be Path, I started writing a function named ContainsInvalidChars (checks to see if said path contains invalid characters), for this I had to use GetDirectoryName & GetFileName but, after writing these 2 methods I stopped and thought to myself:

How do these 2 methods distinguish between the input path being a directory, file or dir + file". I ran a couple of tests and found that they don't. For example, if you had something like C:\\Users\\UserName\\AppData and you were to put this into GetFileName it would return AppData even tho AppData is a folder and technically should be part of the directory and file name should be null, same with GetDirectoryName, even tho AppData is part of the directory name it only returns C:\\Users\\UserName. So I came to the conclusion that I will first have to write a proper GetFileName & GetDirectoryName methods and then only write ContainsInvalidChars. The question still stands, how do I distinguish between the 3 types of path. While thinking about this I started looking for a couple file on my computer when I noticed (something that's easily ignored) the Type column where it shows the type of file/folder, if folder then File folder if file (even without extension) (Ext) File so, here I am. Is there any way to get the file/folder type in C#?

I know that at the end of the day you could always write C:\\Users\\UserName\\AppData\\ and yes, this will be DIR="C:\Users\UserName\AppData" & FILE="" but i know some don't write \\ at the end and just write C:\\Users\\UserName\\AppData.

Upvotes: 0

Views: 732

Answers (2)

er-sho
er-sho

Reputation: 9771

if you are using .net 4.0 and above then there is one way to do this by using below code.

File.GetAttributes("your path to directory or file").HasFlag(FileAttributes.Directory)

But make sure the path is valid.

Or

you may also use

File.Exists();
Directory.Exists(); 

Upvotes: 0

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

System.IO provided functions: File.Exists(string Path) and Directory.Exists(string Path) . Returns boolean value based on value of Path

if (Directory.Exists(@"C:\Users\UserName\AppData\"))
    Console.WriteLine("Folder exists");
else
    Console.WriteLine("Path might be of file");


Ouput:
   Folder exists

Upvotes: 3

Related Questions