【发布时间】:2012-12-05 16:10:45
【问题描述】:
例如,
string path = @"C:\User\Desktop\Drop\images\";
我只需要得到@"C:\User\Desktop\Drop\
有什么简单的方法吗?
【问题讨论】:
例如,
string path = @"C:\User\Desktop\Drop\images\";
我只需要得到@"C:\User\Desktop\Drop\
有什么简单的方法吗?
【问题讨论】:
您可以使用Path 和Directory 类:
DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName;
请注意,如果路径不以目录分隔符字符 \ 结尾,您会得到不同的结果。那么images 会被理解为文件名而不是目录。
你也可以使用Path.GetDirectoryName的后续调用
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
此行为记录在 here:
因为返回的路径不包含 DirectorySeparatorChar 或 AltDirectorySeparatorChar,将返回的路径传递回 GetDirectoryName 方法会导致一个文件夹被截断 每次后续调用结果字符串的级别。 例如,传递 路径“C:\Directory\SubDirectory\test.txt”进入 GetDirectoryName 方法将返回“C:\Directory\SubDirectory”。 将该字符串“C:\Directory\SubDirectory”传递到 GetDirectoryName 将产生“C:\Directory”。
【讨论】:
Directory.GetParent 的解决方案,比字符串操作更安全、更好的方法
var parent = "";
If(path.EndsWith(System.IO.Path.DirectorySeparatorChar) || path.EndsWith(System.IO.Path.AltDirectorySeparatorChar))
{
parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
parent = Directory.GetParent(Path.GetDirectoryName(path)).FullName;
}
else
parent = Path.GetDirectoryName(path);
正如我所评论的,GetDirectoryName 是自我折叠的,它返回路径而不使用斜杠 - 允许获取下一个目录。使用 Directory.GetParent 进行 then clouse 也是有效的。
【讨论】:
简答:)
path = Directory.GetParent(Directory.GetParent(path)).ToString();
【讨论】:
【讨论】:
using System;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string inputText = @"C:\User\Desktop\Drop\images\";
Console.WriteLine(inputText.Substring(0, 21));
}
}
}
输出:
C:\User\Desktop\Drop\
【讨论】:
这将返回 "C:\User\Desktop\Drop\" 例如除了最后一个子目录之外的所有内容
string path = @"C:\User\Desktop\Drop\images";
string sub = path.Substring(0, path.LastIndexOf(@"\") + 1);
如果你有一个斜杠,另一种解决方案:
string path = @"C:\User\Desktop\Drop\images\";
var splitedPath = path.Split('\\');
var output = String.Join(@"\", splitedPath.Take(splitedPath.Length - 2));
【讨论】:
使用 File 或 Path 类可能有一些简单的方法可以做到这一点,但您也可以通过执行以下操作来解决它(注意:未经测试):
string fullPath = "C:\User\Desktop\Drop\images\";
string[] allDirs = fullPath.split(System.IO.Path.PathSeparator);
string lastDir = allDirs[(allDirs.length - 1)];
string secondToLastDir= allDirs[(allDirs.length - 2)];
// etc...
【讨论】: