【问题标题】:What's the difference between GetFullPath(".") and Directory.GetCurrentDirectory()?GetFullPath(\".\") 和 Directory.GetCurrentDirectory() 之间有什么区别?
【发布时间】:2022-12-12 12:03:05
【问题描述】:

这可能是一个微不足道的问题,但我试图了解在这种情况下使用的这两种不同 API 之间的区别。似乎它们是相同的。

我写了一个快速测试程序并在调试模式下查看返回值,这两个 API 返回的值是相同的:

var result = Path.GetFullPath(".");               -> ..\source\\repos\\TestingApp\\TestingAppDotNet\\bin\\Debug
string path = Directory.GetCurrentDirectory();    -> ..\source\\repos\\TestingApp\\TestingAppDotNet\\bin\\Debug

这更像是个人喜好吗?

【问题讨论】:

  • GetFullPath() 下有大量代码来处理可能格式错误的参数值。使用 GetCurrentDirectory() 跳过所有代码。

标签: c#


【解决方案1】:

是的,Path.GetFullPath() 和 Directory.GetCurrentDirectory() 之间的区别主要是偏好问题。这两种方法都返回当前工作目录的完整路径,但 Path.GetFullPath() 允许您指定一个相对路径,而 Directory.GetCurrentDirectory() 总是返回当前目录的完整路径。

在您的示例中,这两种方法都返回相同的结果,因为您将当前目录 (.) 作为输入传递给 Path.GetFullPath()。但是,如果您要指定不同的相对路径,Path.GetFullPath() 将返回该相对路径的完整路径,而 Directory.GetCurrentDirectory() 仍将返回当前目录的完整路径。

这是一个说明差异的示例:

// Returns the full path of the current directory
string currentDirectory = Directory.GetCurrentDirectory(); // ..source\repos\TestingApp\TestingAppDotNet\bin\Debug

// Returns the full path of the parent directory
string parentDirectory = Path.GetFullPath(".."); // ..source\repos\TestingApp\TestingAppDotNet\bin

在此示例中,Directory.GetCurrentDirectory() 仍返回当前目录的完整路径,而 Path.GetFullPath() 返回父目录的完整路径,因为 .. 相对路径已传递给它。

总之,这两种方法都可用于获取当前工作目录的完整路径,但 Path.GetFullPath() 允许您指定相对路径,而 Directory.GetCurrentDirectory() 始终返回当前目录的完整路径。您可以选择最适合您需要的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2018-12-23
    • 2010-11-07
    • 2014-07-20
    • 2011-03-01
    • 2013-02-20
    相关资源
    最近更新 更多