如何从输入获取文件夹/目录路径?

时间:2012-03-07 22:56:14

标签: c# file directory

如果输入是文件夹或文件的路径,如何从用户输入中获取最后一个文件夹/目录?这是当有问题的文件夹/文件可能不存在时。

  

C:\用户\公共\桌面\工作空间\ page0320.xml

     

C:\用户\公共\桌面\工作区

我试图从两个示例中删除文件夹“workspace”,即使文件夹“workspace”或文件“page0320.xml”不存在。

编辑:使用BrokenGlass的建议,我得到了它的工作。

String path = @"C:\Users\Public\Desktop\workspace";
String path2 = @"C:\Users\Public\Desktop\workspace\";
String path3 = @"C:\Users\Public\Desktop\workspace\page0320.xml";

String fileName = path.Split(new char[] { '\\' }).Last<String>().Split(new char[] { '/' }).Last<String>();

if (fileName.Contains(".") == false)
{
    path += @"\";
}

path = Path.GetDirectoryName(path);

您可以替换任何路径变量,输出将是:

C:\Users\Public\Desktop\workspace

当然,这是在文件有扩展的假设下工作的。幸运的是,这个假设适用于我的目的。

谢谢大家。是一个长期潜伏和第一次海报。令人印象深刻的是答案的快速和有用:D

5 个答案:

答案 0 :(得分:3)

使用Path.GetDirectoryName

string path = Path.GetDirectoryName(@"C:\Users\Public\Desktop\workspace\page0320.xml");

string path2 = Path.GetDirectoryName(@"C:\Users\Public\Desktop\workspace\");

请注意第二个示例中路径中的尾部反斜杠 - 否则工作空间将被解释为文件名。

答案 1 :(得分:1)

我将以这种方式使用DirectoryInfo:

DirectoryInfo dif = new DirectoryInfo(path);
if(dif.Exist == true)
    // Now we have a true directory because DirectoryInfo can't be fooled by 
    // existing file names.
else
    // Now we have a file or directory that doesn't exist.
    // But what we do with this info? The user input could be anything
    // and we cannot assume that is a file or a directory.
    // (page0320.xml could be also the name of a directory)

答案 2 :(得分:0)

您可以在GetFileName命名空间中GetDiretoryName类的Path之后使用System.IO

GetDiretoryName将获取没有文件名的路径(C:\Users\Public\Desktop\workspace)。 GetFileName然后返回路径的最后一部分,就好像它是一个无扩展名的文件(workspace)。

Path.GetFileName(Path.GetDirectoryName(path));

编辑:路径必须有一个尾随路径分隔符才能使此示例正常工作。

答案 3 :(得分:0)

如果你能做出一些假设,那么它很容易......

假设1:所有文件都有一个扩展名 假设2:包含目录永远不会有扩展名

If Not String.IsNullOrEmpty(Path.GetExtension(thePath))
  Return Path.GetDirectoryName(thePath)
Else
  Return Path.GetFileName(thePath)
End If

答案 4 :(得分:0)

如前所述,实际上并没有一个可行的解决方案,但这也可以解决问题:

private string GetLastFolder(string path)
{
    //split the path into pieces by the \ character
    var parts = path.Split(new[] { Path.DirectorySeparatorChar, });

    //if the last part has an extension (is a file) return the one before the last
    if(Path.HasExtension(path))
        return parts[parts.Length - 2];

    //if the path has a trailing \ return the one before the last
    if(parts.Last() == "")
        return parts[parts.Length - 2];

    //if none of the above apply, return the last element
    return parts.Last();
}

这可能不是最干净的解决方案,但它会起作用。希望这有帮助!