首页 > 解决方案 > 在 C# 中的 Process.Start 参数中传递引号

问题描述

如何在 C# 的 Process Arguments 中运行此语句。

这一切正常,但我担心如果 mklink 的两个 args 之一有一个空间,这将无法正常工作。所以我在两个参数周围添加了“”。执行此行不再有效,当我写“”时,它仍然无效。

这是我的代码

////Run EXTERNAL APP AS AN ADMIN

string d = "test1234";

SecureString pass = new SecureString();

foreach (char ch in d)
{
    pass.AppendChar(ch);
}
string filepath= @"C:\Program Files (x86)\LalTechnologies\LT_Service\LT_Administration.exe";
string arguments = string.Format("\"{0}\"", filepath);

string filep = arguments;
var process = new Process
{
    StartInfo = new ProcessStartInfo
    {
        UseShellExecute = false,
        //CreateNoWindow = true,
        //WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
        Password = pass,
        UserName = "test",
        Domain = "soft",
        FileName = @"C:\windows\system32\windowspowershell\v1.0\powershell.exe",

        Arguments = $"Start-Process -FilePath "+arguments+$" -Verb RunAs",
       
        RedirectStandardOutput = true,
        RedirectStandardError = true,
    }
};

//*Set your output and error(asynchronous) handlers
   
process.Start();
while (!process.StandardOutput.EndOfStream)
{
    string line = process.StandardOutput.ReadLine();
    // do something with line
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
Start-Process -FilePath "C:\Program Files (x86)\LalTechnologies\LT_Service\LT_Administration.exe" -Verb RunAs

标签: c#

解决方案


使用字符串文字,只需在字符串前面加上 an@并使用双引号(如果您想要引号)。

string quotes = @"this ""string"" has quotes"; // this "string" has quotes

将其与内插字符串一起使用,只需同时使用$@

Arguments = $@"Start-Process -FilePath """+arguments+$@""" -Verb RunAs"

另外我认为您不完全了解$运营商。它将字符串标记为“内插字符串”,允许您执行以下操作

int number = 100;
string score = $"Well done you scored {number}"; // Well done you scored 100

例如,您可以重写Arguments =如下

Arguments = $@"Start-Process -FilePath ""{arguments}"" -Verb RunAs"

推荐阅读