如何从包含通配符的路径中提取目录?

时间:2011-11-17 23:21:23

标签: c# .net file

给出这样的路径:

C:\Temp\SomeDirectory\*.xml

我希望能够区分*.xmlC:\Temp\SomeDirectory

但是,我不希望没有尾部斜杠的目录路径返回其父目录。

这意味着我想要以下行为:

// Wildcard paths return directory
C:\Temp\SomeDirectory\*.csv -> C:\Temp\SomeDirectory

// Trailing slash paths return full path
C:\Temp\SomeDirectory\ -> C:\Temp\SomeDirectory     

// Non-trailing slash paths to a directory return full path
C:\Temp\SomeDirectory -> C:\Temp\SomeDirectory

// Paths to a file return the directory
C:\Temp\SomeDirectory\SomeFileThatExists.csv -> C:\Temp\SomeDirectory

// Paths to a file without an extension (that exists) return the directory
C:\Temp\SomeDirectory\SomeFileThatExistsWithNoExt -> C:\Temp\SomeDirectory

// Paths to a non-existent path without a trailing slash are standard
// Either always clip the trailing part, or always leave it in
// (Can live with this one being C:\Temp\SomeDirectory)
C:\Temp\SomeDirectory\NonExistentObject -> C:\Temp\SomeDirectory\NonExistentObject 

// Paths to a non-existent path with a trailing slash return the full path
C:\Temp\SomeDirectory\NonExistentObject\ -> C:\Temp\SomeDirectory\NonExistentObject

// Paths to a non-existent path with a file extension return the directory
C:\Temp\SomeDirectory\NonExistentFile.Ext -> C:\Temp\SomeDirectory

(如果返回值有一个尾部斜杠,我不会讨厌,虽然我下面的方法一直没有返回斜杠)

我当前的代码是这样的,并处理这些情况:

public string GetDirectory(string path)
{
    try
    {
        var f = new FileInfo(path); // Throws if invalid path, e.g. wildcards

        // Existent directory
        if (Directory.Exists(path))
        {
            // Full path must be a directory, so return full path
            // Ensure to add a trailing slash, as if it's missing it will return parent directory
            return Path.GetDirectoryName(path + '/');
        }

        // Non-existent directory (or ambiguous path without an extension or trailing slash)
        if (!System.IO.File.Exists(path) && String.IsNullOrEmpty(Path.GetExtension(path)))
        {
            // Path is to a non-existent file (without an extension) or to a non-existent directory.
            // As the path does not exist we will standardise and treat it as a directory.
            return Path.GetDirectoryName(path + '/');
        }

        // Path is to a file, return directory
        return Path.GetDirectoryName(path);
    }
    catch (ArgumentException)
    {
        // For wildcards/invalid paths, return the directory
        // This maps C:\Dir\*.csv to C:\Dir
        // Also maps C:\Dir&*A*#$!@& to C:\
        return Path.GetDirectoryName(path);
    }
}

有没有更好的方法来实现这种行为,或者我的最终目标是能够获得"目录"从可能包含通配符的路径?

2 个答案:

答案 0 :(得分:2)

我认为问题在于Path方法只是字符串操作函数。我不相信他们真的会出去找你是在看一个没有扩展名的目录或文件。

您需要结合使用Directory或File类来找出它,然后相应地手动更改它。

答案 1 :(得分:2)

您是否可以控制路径列表的生成?如果你可以确保目录的所有路径都以尾部斜杠结尾(我认为这是惯例),那么简单的Path.GetDirectoryName(path)将适用于所有这些情况。

相关问题