【问题标题】:Why does Directory.Exists("%HOMEPATH%") == true with .Net Core Console but not Windows Desktop Console?为什么 Directory.Exists("%HOMEPATH%") == true 使用 .Net Core 控制台而不是 Windows 桌面控制台?
【发布时间】:2018-10-03 12:17:10
【问题描述】:

我有两个控制台可执行文件,每个都使用同一个库。一个 exe 是使用 .Net Core 编写的,另一个是使用 Windows 桌面控制台编写的。在使用 .Net Standard 编写的库中,我有一个通用代码,包括一个验证命令行参数的方法,该参数可能具有一个目录位置作为字符串。在两者的项目属性中,我都有一个 Debug 'Start option > Command line argument' "%HOMEPATH%\Documents\'。当 .Net Core 程序使用 .Net 标准库时,它会找到该文件夹​​,但当 Windows 桌面程序使用相同的库时,找不到该目录!为什么?

项目调试启动选项命令行参数值: "%HOMEPATH%\Documents"

.Net 标准库中的代码:

public static void ValidateWorkingDirectory(ref string workingDirectory)
{
    if (!Directory.Exists(workingDirectory))
    {
        Log.Warning("The working directory argument is not valid! Arg: {0}. Defaulting to current running directory: {1}", workingDirectory, Environment.CurrentDirectory);
        workingDirectory = Environment.CurrentDirectory;
    }
}

有趣的是,如果我把%HOMEPATH%\Documents 放到项目属性/Debug/Working 目录下也是类似的。在 .Net Core 项目上很好,但在 Windows 桌面控制台上显示对话框“工作目录不存在。”

非常感谢您的帮助。

【问题讨论】:

  • 这是 Unix 和 Windows 之间不那么微妙的区别。桌面版本从未打算以 Unix 为目标,但 .NETCore 确实如此(MacOS 和许多 Linux 版本)。 Unix 程序员从没想过自己必须扩展环境变量,shell 总是为他做这件事。您应该能够使用 Environment.ExpandEnvironmentVariables() 使差异消失。

标签: c# .net .net-core .net-standard


【解决方案1】:

方法 Directory.Exists 在标准 .Net 框架中需要绝对或相对目录路径,像 '%HOMEPATH%' 这样的盟友不起作用。在这种情况下,此方法会尝试查找名为“%HOMEPATH%”的文件夹。这种行为在 .Net Core 中可能有所不同。

要让它工作,你需要使用类似的东西:

var envVariable = System.Environment.GetEnvironmentVariable("HOMEPATH");
var isExists = System.IO.Directory.Exists(envVariable);

请记住,GetEnvironmentVariable 的值不包含“%”。

有关更多信息,请查看以下内容: https://docs.microsoft.com/en-us/previous-versions/windows/desktop/sidebar/system-environment-getenvironmentvariable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多