【问题标题】:Path.GetDirectoryName() isn't returning ArgumentException for empty path in .net corePath.GetDirectoryName() 没有为 .net 核心中的空路径返回 ArgumentException
【发布时间】:2018-12-28 13:27:21
【问题描述】:

我正在将我的代码从 .Net Framework 迁移到 .Net Core,我在 API 中看到一个名为 Path.GetDirectoryName() 的回归。虽然我将一个空值(即“”)传递给它,但它并没有返回我 System.ArgumentException 而是返回我 null 值。

这曾经在 .Net Framework 中运行良好,根据文档,这就是 .Net Core 中的行为方式:

// 例外:

// T:System.ArgumentException:

// 路径参数包含无效字符,为空,或 仅包含白色 // 空格。

【问题讨论】:

  • 我投票结束这个问题,因为它似乎描述了一个应该报告的错误。没有问题。

标签: c# asp.net-core .net-core asp.net-core-2.2


【解决方案1】:

来自corefxSystem.IO.Path.GetDirectoryName 方法的文档:

/// <summary>
/// Returns the directory portion of a file path. This method effectively
/// removes the last segment 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
/// specified path is null, empty, or a root (such as "\", "C:", or
/// "\\server\share").
/// </summary>
/// <remarks>
/// Directory separators are normalized in the returned string.
/// </remarks>
public static string GetDirectoryName(string path)
{
    if (path == null || PathInternal.IsEffectivelyEmpty(path.AsSpan()))
        return null;

    int end = GetDirectoryNameOffset(path.AsSpan());
    return end >= 0 ? PathInternal.NormalizeDirectorySeparators(path.Substring(0, end)) : null;
}

所以,它与完整框架版本不同,如果 指定的路径为 null、空或根。这是预期的行为

【讨论】:

  • 啊,我明白了,但是文档也应该更改,当我从 Visual Studio 执行 GetDefinition 时,我发现与 .Net Framework 的文档相同。
猜你喜欢
  • 2018-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
相关资源
最近更新 更多