I want to determine if a folder contains a file, when both are specified by a path.
At first glance this seems simple. Just check if the file path starts with the directory path. However, this naive check ignores several issues:
- Paths may be relative or absolute
- Paths may use the alternate directory separator
- Paths may use inconsistent casing, which matters depending on the OS
- Different paths may refer to the same location
- Probably some more that I don't know about
Is there an existing method in the framework, or do I have to write my own?
As far as I know, there is no built-in .NET method to do this, but the following function should accomplish this using the FileInfo and DirectoryInfo classes:
public static bool FolderContainsFile(String folder, String file)
{
//Create FileInfo and DirectoryInfo objects
FileInfo fileInfo = new FileInfo(file);
DirectoryInfo dirInfo = new DirectoryInfo(folder);
DirectoryInfo currentDirectory = fileInfo.Directory;
if (dirInfo.Equals(currentDirectory))
return true;
while (currentDirectory.Parent != null)
{
currentDirectory = currentDirectory.Parent;
if(currentDirectory.Equals(dirInfo)
return true;
}
return false;
}
I'm not sure if it'll work in all cases, but I'd suggest looking at Path.GetFullPath.
Quote: Returns the absolute path for the specified path string.