2012-04-19 68 views
3

我已通過以下代碼使用C#成功打開命令提示符窗口。如何使用C#在命令提示符下更改目錄位置?

Process p = new Process(); 
    p.StartInfo.FileName = "cmd.exe"; 
    p.StartInfo.WorkingDirectory = @"d:\pdf2xml"; 
    p.StartInfo.WindowStyle = ProcessWindowStyle.Normal; 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 
    p.StartInfo.RedirectStandardInput = true; 


    p.Start(); 

    p.StandardInput.WriteLine(@"pdftoxml.win32.1.2.7 -annotation "+filename); 

    p.StandardInput.WriteLine(@"cd D:\python-source\ds-xmlStudio-1.0-py27"); 

    p.StandardInput.WriteLine(@"main.py -i example-8.xml -o outp.xml"); 

    p.WaitForExit(); 

但是,我也通過命令來改變目錄。

問題:

  1. 如何更改目錄位置?
  2. 命令提示符將顯示始終打開後...

請指引我走出這些問題的...

回答

10

您可以使用p.StandardInput.WriteLine將命令發送到CMD窗口。爲此,只需將p.StartInfo.RedirectStandardOutput設置爲true即可。如下所示

 Process p = new Process(); 
     p.StartInfo.FileName = "cmd.exe"; 
     //p.StartInfo.Arguments = @"/c D:\\pdf2xml"; 
     p.StartInfo.UseShellExecute = false; 
     p.StartInfo.RedirectStandardOutput = true; 
     p.StartInfo.RedirectStandardInput = true; 
     p.Start(); 

     p.StandardInput.WriteLine(@"cd D:\pdf2xml"); 
     p.StandardInput.WriteLine("d:"); 
+0

@ Waqar:謝謝Waqar.Cmd提示windwod沒有顯示任何東西,我認爲它因爲p.StartInfo.RedirectStandardInput = true而被絞死; 這一行... – Saravanan 2012-04-19 05:38:48

+0

@ Waqar:我必須使用這個命令。 main.py -i example-8.xml -o result.xml.But它不會顯示任何東西。在普通的cmd提示符下工作正常。這裏有什麼問題... – Saravanan 2012-04-19 06:33:23

+0

@Saravanan如果你想讀取輸出你需要調用下面的String output = p.StandardOutput.ReadToEnd(); – Waqar 2012-04-19 07:58:36

1

使用System.IO.Directory.SetCurrentDirectory代替

您還可以檢查this

and this post

processStartInfo .WorkingDirectory = @"c:\"; 
+0

對於'processStartInfo .WorkingDirectory = @「c:\」;'!!! :) – Sonhja 2013-10-30 16:22:25

11

要更改啓動目錄,可以通過將p.StartInfo.WorkingDirectory設置爲您感興趣的目錄來更改啓動目錄。您的目錄未更改的原因是因爲參數/c d:\test。相反,嘗試/c cd d:\test

Process p = new Process(); 
p.StartInfo.FileName = "cmd.exe"; 
p.StartInfo.WorkingDirectory = @"C:\"; 
p.StartInfo.UseShellExecute = false; 
... 
p.Start(); 

你可以通過設置p.StartInfo.WindowStyle爲隱藏,以避免顯示該窗口隱藏命令提示符。

p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 

http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.windowstyle.aspx

相關問題