【问题标题】:how to change the directory location in command prompt using C#?如何使用 C# 在命令提示符下更改目录位置?
【发布时间】:2012-04-19 05:11:32
【问题描述】:

我已经通过以下代码使用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. 打开后会一直显示Cmd提示...

请指导我摆脱这些问题...

【问题讨论】:

    标签: c# c#-4.0 process directory


    【解决方案1】:

    您可以使用 p.StandardInput.WriteLine 将命令发送到 cmd 窗口。为此,只需将 p.StartInfo.RedirectStandardOutput 设置为 ture。如下所示

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

    【讨论】:

    • @Waqar: 谢谢Waqar.Cmd 提示windwod 没有显示任何东西。我认为它被挂起是因为p.StartInfo.RedirectStandardInput = true;这一行……​​
    • @Waqar :我必须使用这个命令。 main.py -i example-8.xml -o result.xml。但它不会显示任何东西。在正常的cmd提示符下它工作正常。这里有什么问题......
    • @Saravanan 如果您想读取命令的输出,那么您需要调用以下 String output = p.StandardOutput.ReadToEnd();
    • @ Waqar :不,实际上我无法通过 C# 调用此命令 main.py -i example-8.xml -o result.xml。这是我想从 C# 运行的 python 代码.这个程序接受一个输入的xml文件并生成另一个xml文件。
    • @Saravanan Actully 我不知道 python commnds。但我可以建议您确保将 main.pi 和输入 xml 文件都放置到您从 cmd 移动目录位置的路径
    【解决方案2】:

    改用System.IO.Directory.SetCurrentDirectory

    您也可以查看this

    and this post

    processStartInfo .WorkingDirectory = @"c:\";
    

    【讨论】:

      【解决方案3】:

      要更改启动目录,您可以通过将 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 设置为 Hidden 来隐藏命令提示符以避免显示该窗口。

       p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-21
        • 2015-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-13
        • 2013-09-08
        相关资源
        最近更新 更多