如何从输入中获取文件夹/目录路径?
你如何获得最后一个文件夹/目录了用户输入的不论如果输入到一个文件夹或文件的路径?这是当问题的文件夹/文件可能不存在。如何从输入中获取文件夹/目录路径?
C:\用户\公用\桌面\工作区\ page0320.xml
C:\用户\公用\桌面\ 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
当然,这是有文件扩展名assuption下工作。幸运的是,这个假设适用于我的目的。
谢谢大家。曾经是一个长期的潜伏者和第一次海报。这是真是令人印象深刻的快速和乐于助人的反应如何为:d
使用Path.GetDirectoryName
:
string path = Path.GetDirectoryName(@"C:\Users\Public\Desktop\workspace\page0320.xml");
string path2 = Path.GetDirectoryName(@"C:\Users\Public\Desktop\workspace\");
注意路径尾部的反斜杠,虽然在第二个例子 - 否则工作空间将被解释为文件名。
可以在System.IO
名称空间中的Path
类的GetDiretoryName
之后使用GetFileName
。
GetDiretoryName
将得到路径,而不文件名(C:\Users\Public\Desktop\workspace
)。 GetFileName
然后返回路径的最后一部分,就好像它是一个扩展名的文件(workspace
)。
Path.GetFileName(Path.GetDirectoryName(path));
编辑:该路径必须有一个拖尾路径分隔符,使此示例工作。
对“C:\ Users \ Public \ Desktop \ workspace”运行的代码将生成“Desktop” – 2012-03-07 23:04:32
只有在两个假设中的一个为真时,才有可能这样做:文件始终具有扩展名,或者路径始终具有尾随分隔符。 – DaveShaw 2012-03-07 23:09:45
如果你可以做一些假设,那么它很容易..
假设1:所有的文件都会有一个扩展 假设2:含目录将永远不会有一个扩展
If Not String.IsNullOrEmpty(Path.GetExtension(thePath))
Return Path.GetDirectoryName(thePath)
Else
Return Path.GetFileName(thePath)
End If
我会通过这种方式使用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)
就像之前说的那样,没有一个真正可行的解决方案,但是这也可以做到这一点:
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();
}
这可能不是最干净的解决方案,但它会工作。希望这可以帮助!
目录路径通常不包含尾部反斜杠 – 2012-03-07 23:05:22
这是OP问题的唯一可行解决方案。该目录不存在,所以你不能检查,没有这个方法无法区分文件和目录名称 - 我指出这可能会回答。 – BrokenGlass 2012-03-07 23:07:34
我想最好的折衷办法是查看文件名是否包含句点,如果不添加尾部反斜杠。谢谢。 – Abion47 2012-03-07 23:40:36