c# - Path.GetDirectoryName 是如何工作的?

标签 c# path openfiledialog

当我使用OpenFileDialog 打开文件时,当然我需要获取文件目录 及其名称 来加载文件。(加载 xml,访问我需要完整路径的文件。)

opdOpenFileDialog

        if (opd.ShowDialog() == true)
        {
            var names = opd.FileNames;

            foreach (string name in names)
            {
                LoadFile(Path.Combine(Path.GetDirectoryName(name), name));
            }
        }

我的问题是 Path.GetDirectoryName 如何通过仅获取字符串来获取文件的路径?

Path.GetDirectoryName(name)

name 只是 string 并且此方法仅通过获取字符串来获取其目录? .计算机中可以有数千个同名文件。

简短问题: opd refrenced 在哪里?

编辑:

我以为 opd.FileNames 只是获取文件的 name。(因为方法名称)

而且我还发现了一些有趣的东西。

LoadFile(Path.Combine(Path.GetDirectoryName(name), name));

这很好用,因为 Path.Combine 将跳过字符串的相同部分。

例如:

string name = @"C:\Users\Default\xml.xml";
string getDirNameResault= Path.GetDirectoryName(name);// this will be C:\Users\Default

所以 Path.Combine 将是

 Path.Combine(@"C:\Users\Default", @"C:\Users\Default\xml.xml)

女巫返回 "C:\Users\Default\xml.xml" !

最佳答案

Path.GetDirectoryName 通过斜杠 /\ 拆分您已有的字符串(来自 opd)和然后返回除最后一部分以外的所有内容。

.NET Core 基础库(称为 CoreFX)中函数的完整源代码,您可以在此处找到:https://github.com/dotnet/corefx/blob/41e203011152581a6c65bb81ac44ec037140c1bb/src/System.Runtime.Extensions/src/System/IO/Path.cs#L151

实现代码:

// Returns the directory path of a file path. This method effectively
// removes the last element of the given file path, i.e. it returns a
// string consisting of all characters up to but not including the last
// backslash ("\") in the file path. The returned value is null if the file
// path is null or if the file path denotes a root (such as "\", "C:", or
// "\\server\share").
//
public static String GetDirectoryName(String path)
{
    if (path != null)
    {
        CheckInvalidPathChars(path);

#if FEATURE_LEGACYNETCF
        if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
        {
#endif

            string normalizedPath = NormalizePath(path, false);

            // If there are no permissions for PathDiscovery to this path, we should NOT expand the short paths
            // as this would leak information about paths to which the user would not have access to.
            if (path.Length > 0)
            {
                try
                {
                    // If we were passed in a path with \\?\ we need to remove it as FileIOPermission does not like it.
                    string tempPath = Path.RemoveLongPathPrefix(path);

                    // FileIOPermission cannot handle paths that contain ? or *
                    // So we only pass to FileIOPermission the text up to them.
                    int pos = 0;
                    while (pos < tempPath.Length && (tempPath[pos] != '?' && tempPath[pos] != '*'))
                        pos++;

                    // GetFullPath will Demand that we have the PathDiscovery FileIOPermission and thus throw 
                    // SecurityException if we don't. 
                    // While we don't use the result of this call we are using it as a consistent way of 
                    // doing the security checks. 
                    if (pos > 0)
                        Path.GetFullPath(tempPath.Substring(0, pos));
                }
                catch (SecurityException)
                {
                    // If the user did not have permissions to the path, make sure that we don't leak expanded short paths
                    // Only re-normalize if the original path had a ~ in it.
                    if (path.IndexOf("~", StringComparison.Ordinal) != -1)
                    {
                        normalizedPath = NormalizePath(path, /*fullCheck*/ false, /*expandShortPaths*/ false);
                    }
                }
                catch (PathTooLongException) { }
                catch (NotSupportedException) { }  // Security can throw this on "c:\foo:"
                catch (IOException) { }
                catch (ArgumentException) { } // The normalizePath with fullCheck will throw this for file: and http:
            }

            path = normalizedPath;

#if FEATURE_LEGACYNETCF
        }
#endif

        int root = GetRootLength(path);
        int i = path.Length;
        if (i > root)
        {
            i = path.Length;
            if (i == root) return null;
            while (i > root && path[--i] != DirectorySeparatorChar && path[i] != AltDirectorySeparatorChar) ;
            String dir = path.Substring(0, i);
#if FEATURE_LEGACYNETCF
            if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
            {
                if (dir.Length >= MAX_PATH - 1)
                    throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
            }
#endif
            return dir;
        }
    }
    return null;
}

有关函数的完整源代码(在 Mono 中),请参见此处:https://github.com/mono/mono/blob/master/mcs/class/corlib/System.IO/Path.cs#L199

关于c# - Path.GetDirectoryName 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30777674/

相关文章:

c# - Buffer.BlockCopy C# 出现奇怪的数据损坏

PHP 需要 realpath - 需要打开失败

matlab - 如何在MATLAB中编写相对路径?

c# - 服务在不同路径中写入文件

c# - 继续打开 OpenFileDialog 直到选择有效文件

c++ - 如何在 Windows 公用文件对话框中显示 API 填充的虚拟文件夹

C# 不要在 OpenFileDialog 中显示过滤器扩展

c# - 我的 clickonce 应用程序如何请求编辑注册表和主机文件的权限?

c# - 从 C# 中的对象类型获取数据

c# - ASP.Net MVC5 Html.ActionLink 在不同 Controller 中索引方法