How can I identify whether a deleted path was a file or a directory using C# .Net?
thanks
How can I identify whether a deleted path was a file or a directory using C# .Net?
thanks
If you use Directory.Exists(...) on a file it will return false. Likewise if you use File.Exists(...) on a directory it will return false
Assuming that the file/directory actually exists, you can use the two static methods:
Both accept a single string argument and returns a boolean value if the file/directory exists.
Another case is when you have a path that does not refer to an existing file/directory in the file system - maybe it points to some kind of "virtual file/directory" in a database, or the path points to a file/directory that used to exists, but is now (possibly) deleted. In this case, you will have to define the distinction of "file like paths" and "directory like paths" yourself. I can think of two approaches:
Lets test the two approaches on a couple of sample input strings:
c:\windows\
is a directory in both casesc:\windows
is a directory only when using approach Bc:\windows\notepad.exe
is a file in both casesc:\windows\system32\drivers\etc\hosts
is a file only in approach AAs pointed out by these examples, none of the two approaches are guaranteed to give the expected answers in all cases, unless you are able to control exactly how the paths are designed from the beginning.
use File.Exists() or Directory.Exists(). They will tell you if there is a file / directory with that name. You then know what it is by checking which one returns treu.
also you can use: path.GetFileName
If the last character of path is a directory or volume separator character, this method returns Empty, so you can check the result if it's empty so it's a directory else it's a file.
If you have an extension then you could guess it was a file, but that would be a guess because you can always name your folder "myfile.txt". Another guess as mentioned would be if it ended in a path separator.
File.Exists and Directory.Exists both use GetFileAttributesEx which look at the attributes of a file, but as it's no longer there you don't have that option. If it's in the recycle bin you may be able to find it there - this question has details.
You can use
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetError = true)]
static extern int GetFileAttributes(string lpFileName);
bool IsDirectory(string path) {
return GetFileAttributes(path) & 16 == 16;
}
However Directory.Exists
and File.Exists
as suggested in the other answers is just as good.
See here for more details.