【问题标题】:Spaces in file path not working with @ or \" (C#)文件路径中的空格不适用于 @ 或 \" (C#)
【发布时间】:2015-12-27 20:58:05
【问题描述】:

在发布之前,我已尝试尽职尽责地进行搜索,但在 C# 应用程序中启动 powershell 脚本时,我遇到了文件路径中的空格问题。我尝试过转义引号,几乎在任何地方都使用 @ 单引号。我在这里想念什么?

这就是我定义路径的方式:

public string importMusicLocation = @"C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1";

然后我启动一个 powershell 进程并指向路径,以前我在指向桌面上的路径时可以正常工作,没有空格,但现在我想将应用程序放在 Program Files 中,powershell 窗口只检测到通往空间的路径。

private void LaunchPshell(string script) {
    string strCmdText = Path.Combine(Directory.GetCurrentDirectory(), script);

    var process = System.Diagnostics.Process.Start(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe", strCmdText);
    process.WaitForExit();
}

在我发布此内容 5 分钟后,我意识到我不需要合并目录,我将删除此内容,但我可以发布解决方案以防其他人需要它。 powershell 启动脚本的一般语法是& 'C:\Program Files\Some Path':

public string importMusicLocation = @"& 'C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1'";

private void LaunchPshell(string script) {
    var process = System.Diagnostics.Process.Start(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe", script);
    process.WaitForExit();
}

【问题讨论】:

  • 您的问题是什么?顺便说一句,如果文件或文件夹的名称中有两个或更多相邻的空格,您接近 @"& 'C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1'" 将失败。

标签: c# powershell path filepath


【解决方案1】:

尝试用双引号引用您的路径值,例如

string importMusicLocation = @"""C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1""";

因此,PowerShell.exe 实用程序会将参数作为带引号的字符串接收,因此不应出现间距问题

"C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1"

【讨论】:

  • 这是有效的代码,但它实际上并没有在 powershell 中执行脚本。输出:PS C:\WINDOWS\system32> "C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1" C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1
  • @nkasco prepend &
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
相关资源
最近更新 更多