简体   繁体   English

无论尾部斜杠如何,都从完整目录路径获取目录名称

[英]Get directory name from full directory path regardless of trailing slash

I need to get the directory name from its path regardless of any of having a trailing backslash. 我需要从其路径获取目录名称,而不管是否有任何尾部反斜杠。 For example, user may input one of the following 2 strings and I need the name of logs directory: 例如,用户可以输入以下2个字符串之一,我需要日志目录的名称:

"C:\Program Files (x86)\My Program\Logs"
"C:\Program Files (x86)\My Program\Logs\"

None of the following gives correct answer ( "Logs" ): 以下所有内容均未给出正确答案( "Logs" ):

Path.GetDirectoryName(m_logsDir);
FileInfo(m_logsDir).Directory.Name;

They apparently analyze the path string and in the 1st example decide that Logs is a file while it's really a directory. 他们显然分析了路径字符串,并在第一个例子中确定Logs是一个文件,而它实际上是一个目录。

So it should check if the last word ( Logs in our case) is really a directory; 所以它应该检查最后一个字(在我们的例子中是Logs )是否真的是一个目录; if yes, return it, if no (Logs might be a file too), return a parent directory. 如果是,则返回它,如果没有(日志也可能是文件),则返回父目录。 If would require dealing with the actual filesystem rather than analyzing the string itself. 如果需要处理实际的文件系统而不是分析字符串本身。

Is there any standard function to do that? 有没有标准功能呢?

new DirectoryInfo(m_logsDir).Name;

This may help 这可能有所帮助

var result = System.IO.Directory.Exists(m_logsDir) ? 
              m_logsDir: 
              System.IO.Path.GetDirectoryName(m_logsDir);

For this we have a snippet of code along the lines of: 为此,我们提供了一段代码:

m_logsDir.HasFlag(FileAttribute.Directory); //.NET 4.0

or 要么

(File.GetAttributes(m_logsDir) & FileAttributes.Directory) == FileAttributes.Directory; // Before .NET 4.0

Let me rephrase my answer, because you have two potential flaws by the distinguishing factors. 让我重新解释一下我的答案,因为你有两个潜在的缺陷就是区别因素。 If you do: 如果你这样做:

var additional = @"C:\Program Files (x86)\My Program\Logs\";
var path = Path.GetDirectoryName(additional);

Your output would be as intended, Logs . 您的输出将符合预期, Logs However, if you do: 但是,如果你这样做:

var additional = @"C:\Program Files (x86)\My Program\Logs";
var path = Path.GetDirectoryName(additional);

Your output would be My Program , which causes a difference in output. 您的输出将是My Program ,这会导致输出的差异。 I would either try to enforce the ending \\ otherwise you may be able to do something such as this: 我会尝试强制执行结束\\否则你可能会做这样的事情:

var additional = @"C:\Program Files (x86)\My Program\Logs";
var filter = additional.Split('\\');
var getLast = filter.Last(i => !string.IsNullOrEmpty(i));

Hopefully this helps. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM