gpt4 book ai didi

c# - 文件路径中的空格问题 - C# 中的命令行执行

转载 作者:行者123 更新时间:2023-11-30 13:28:45 25 4
gpt4 key购买 nike

我正在为命令行程序构建一个图形用户界面。在 txtBoxUrls[TextBox] 中逐行输入文件路径。如果文件路径包含空格,则程序无法正常运行。程序如下。

string[] urls = txtBoxUrls.Text.ToString().Split(new char[] { '\n', '\r' });

string s1;
string text;
foreach (string s in urls)
{
if (s.Contains(" "))
{
s1 = @"""" + s + @"""";
text += s1 + " ";
}
else
{
text += s + " ";
}
}


System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = true;


proc.StartInfo.FileName = @"wk.exe";


proc.StartInfo.Arguments = text + " " + txtFileName.Text;

proc.StartInfo.UseShellExecute = false;


proc.StartInfo.RedirectStandardOutput = true;


proc.Start();

//Get program output
string strOutput = proc.StandardOutput.ReadToEnd();

//Wait for process to finish
proc.WaitForExit();

例如,如果在txtBoxUrls 中输入的文件路径是“C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm”,程序将无法运行。这个带双引号的文件路径将在 Windows 命令行中很好地工作(我没有使用 GUI)。解决方案是什么。

最佳答案

proc.StartInfo.Arguments = text + " " + txtBoxUrls.Text + " " + txtFileName.Text; 

在此行中,text 已包含正确引用的 txtBoxUrls 字符串版本。为什么要以不带引号的形式再次添加它们 (+ txtBoxUrls.Text)?如果我正确理解了您的代码,则以下内容应该有效:

proc.StartInfo.Arguments = text + " " + txtFileName.Text;    

事实上,由于 txtFileName.Text 可能包含空格,您也应该引用它,以确保:

proc.StartInfo.Arguments = text + " \"" + txtFileName.Text + "\"";    

(或者,使用你的语法:)

proc.StartInfo.Arguments = text + @" """ + txtFileName.Text + @"""";    

关于c# - 文件路径中的空格问题 - C# 中的命令行执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4185633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com