I am trying to determine whether a given path points to a file or a directory. Currently my logic is very plain and involves the following check
if (sourcePath.Contains(".")) // then treat this path as a file
The problem above is that folder names can have periods in them too. I would like to be able to ascertain that a given path is that of a file wit开发者_StackOverflowhout having to try and instantiate a filestream type and attempting to access it or anything like that.
Is there someway to do this?
Thanks in advance
You could use the File.Exists method:
If path describes a directory, this method returns false
So:
if (File.Exists(sourcePath))
{
// then treat this path as a file
}
There's also the Directory.Exists method and the following example is given in the documentation:
if(File.Exists(path))
{
// This path is a file
ProcessFile(path);
}
else if(Directory.Exists(path))
{
// This path is a directory
ProcessDirectory(path);
}
else
{
Console.WriteLine("{0} is not a valid file or directory.", path);
}
C#:
public bool IsFolder(string path)
{
return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}
VB.Net:
Public Function IsFolder(path As String) As Boolean
Return ((File.GetAttributes(path) And FileAttributes.Directory) = FileAttributes.Directory)
End Function
This function throws a File not found exception
if the file does not exists. So you have to catch it (or use Darin Dimitrow's approach).
Try
Dim isExistingFolder As Boolean = IsFolder(path)
Dim isExistingFile = Not isExistingFolder
Catch fnfEx As FileNotFoundException
'.....
End Try
var isDirectory = (File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory;
System.IO.File.Exists("yourfilenamehere")
will do the trick. This'll return false if the path isn't for a file. It'll also return false if the path doesn't exist, so be careful.
by googling, I found this:
public bool IsFolder(string path)
{
return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}
then you can call the function as follows:
// Define a test path
string filePath = @"C:\Test Folder\";
if (IsFolder(filePath)){
MessageBox.Show("The given path is a folder.");
}
else {
MessageBox.Show("The given path is a file.");
}
List<string> RtnList = new List<string>();
foreach (string Line in ListDetails)
{
if (line.StartsWith("d") && !line.EndsWith("."))
{
RtnList.Add(line.Split(' ')[line.Split(' ').Length - 1] );
}
}
精彩评论