how to change the directory location in command prompt using C#?

蓝咒 提交于 2020-01-12 07:59:46

问题


I have successfully opened command prompt window using C# through the following code.

    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();

But, i have also passed command to change the directory.

problems:

  1. how to change the directory location?
  2. Cmd prompt will be shown always after opened...

Please guide me to get out of those issue...


回答1:


You can use p.StandardInput.WriteLine to send commands to cmd window. For this just set the p.StartInfo.RedirectStandardOutput to ture. like below

        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:");



回答2:


To change the startup directory, you can change it by setting p.StartInfo.WorkingDirectory to the directory that you are interested in. The reason that your directory is not changing is because the argument /c d:\test. Instead try /c cd d:\test

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

You can hide the command prompt by setting p.StartInfo.WindowStyle to Hidden to avoid showing that window.

 p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

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




回答3:


use System.IO.Directory.SetCurrentDirectory instead

You may also Check this

and this post

processStartInfo .WorkingDirectory = @"c:\";


来源:https://stackoverflow.com/questions/10222004/how-to-change-the-directory-location-in-command-prompt-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!