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

时间:2012-03-01 09:24:51

标签: c# process

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

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

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

4 个答案:

答案 0 :(得分:14)

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

var processStartInfo = new ProcessStartInfo();
processStartInfo.WorkingDirectory = @"c:\";
processStartInfo.FileName = "cmd.exe";

// set additional properties     
Process proc = Process.Start(processStartInfo);

答案 1 :(得分:1)

修改 其他人发布了更有说服力的解决方案,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提示打开。)

...如果您的唯一目标是启动命令提示符,但我建议将它们包装在错误处理中,例如....

  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#专家可以随时纠正我。

答案 2 :(得分:1)

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

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

更多信息:Cmd parameters

答案 3 :(得分:1)

var process = Process.Start(new ProcessStartInfo
                            {
                                WorkingDirectory = "C:\\",
                                FileName="cmd.exe"
                            });