.net cmd Proces.Start()无法更改目录

我认为我的问题标题已经非常明确了。

我通过传递“cmd.exe”作为参数来调用Process.Start()方法。 但不知何故,当我执行程序时,出现的命令提示符将我的项目文件夹中的.../bin/debug/作为其目录。 我希望它改为C:而不是。

有人可以就此提出建议吗?

这是为任何类型的进程设置指定工作目录的正确方法:

 var processStartInfo = new ProcessStartInfo(); processStartInfo.WorkingDirectory = @"c:\"; processStartInfo.FileName = "cmd.exe"; // set additional properties Process proc = Process.Start(processStartInfo); 
 var process = Process.Start(new ProcessStartInfo { WorkingDirectory = "C:\\", FileName="cmd.exe" }); 

除了此处描述的解决方案之外, cmd.exe的参数还可以接受在命令行打开后立即执行的命令。 此外,还有/k开关,它将在执行命令后保持命令行运行。 您可以使用这两件事来实现目标:

 Process.Start("cmd.exe", @"/k ""cd /d C:\"""); 

更多信息: Cmd参数 。

编辑:其他人已发布更多雄辩的解决方案,一个la Yuriy-Guts的… Process.Start("cmd.exe", @"/k ""cd /d C:\""");

(这个怎么运作:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true

…’/ k’是后执行命令的一部分,它会在目录更改后保持cmd提示符处于打开状态。)

…如果您的唯一目标是启动命令提示符,但我建议将它们包装在error handling中,例如……

  try { Process.Start("cmd.exe", @"/k ""cd /d C:\"""); } catch(Exception e) { //Just in case... Console.WriteLine(e.ToString()); string[] str=Directory.GetLogicalDrives(); Console.WriteLine( "Using C# Directory Class ,Available drives are:"); for(int i=0;i< str.Length;i++) Console.WriteLine(str[i]); //If fatal //Environment.Exit(1) } 

此外,如果您在C中做其他事情:/我相信以下解决方案是最透明的。

简答:您的IDE会自动将您转储到调试目录中,因为这是编程放置可执行文件的路径。 您的可执行文件对System对象的引用是它所在的文件夹。您必须使用绝对索引来到达根位置C:您想要去。

代码,自助建议的长答案首先尝试Google,了解基础知识: https : //www.google.com/search? q = change + directory = c%23

第一个结果: http : //www.c-sharpcorner.com/UploadFile/chandrahundigam/WorkingWithDirectory07022005012852AM/WorkingWithDirectory.aspx

(它的格式很差,但包含很好的内容。)

用来解释:

添加到您的代码:

 using System; using System.IO; using System.MarshalByRefObject; class DoStuff { char driveLetter; ... void Initialize() { try { Directory.SetCurrentDirectory( string(driveLetter)+string(@":\"); } catch(FileNotFoundException e) { //Just in case... Console.WriteLine(e.ToString()); string[] str=Directory.GetLogicalDrives(); Console.WriteLine( "Using C# Directory Class ,Available drives are:"); for(int i=0;i< str.Length;i++) Console.WriteLine(str[i]); //If fatal //Environment.Exit(1) } Process.Start("cmd.exe"); //Do whatever else you need to do in C:/ ... } 

注意我是C#的新手,并没有明确知道如何做到这一点,但要弄清楚它是相对微不足道的。 如果我的方法有任何缺陷,C#专家可以随意纠正我。