C#执行CMD代码为什么CMD默认路径会自动跳到项目程序当前路径?

来源:百度知道 编辑:UC知道 时间:2024/05/15 01:53:52
public static string RunCmd(string [] cmd)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.StandardInput.AutoFlush = true;
string strRst = string.Empty;
for (int i = 0; i < cmd.Length; i++)
{
p.StandardInput.WriteLine(cmd[i].ToString());
p.StandardInput.WriteLine("exit");
strRst += p.StandardOutput.ReadToEnd();
}

p.WaitForExit();
p.Close();
return strRst;
}
这个是CMD执行的源C#代码.我在程

是这样的,任何时刻你的应用都有一个“工作目录”,指示当前在哪个目录上工作。在没有使用其他方法更改的时候,如果是在debug下调试,工作目录就是debug\bin,同理release。

使用TreeView打开文件时,工作目录并不会改变,如果此时没有使用全路径的话,cmd会找不到要删除的文件的。

而openFile工作方式却不一样,它在打开文件夹的同时就把工作目录更改过去了,此时使用相对路径是不会出问题的。

使用对象浏览器查看openFile的属性和方法你会找到RestoreDirectory属性,默认是false,意为openFile对话框关闭时工作目录会停留在你打开的文件夹下。如果该属性置为true,对话框关闭后工作目录会还原到调用openFile前的目录。

使用TreeView的话,还是尽可能返回文件的全路径吧。可以使用Node的FullPath来配合取得节点的全路径。

cmd用全路径