简体   繁体   English

c#执行命令行如命令提示符?

[英]c# execute command line like command prompt?

I want to write ac# code to execute some command prompt lines and store the result into a global variable in c# to be used for further processing in other part of the code in c#. 我想编写ac#代码来执行一些命令提示行并将结果存储到c#中的全局变量中,以便在c#的代码的其他部分中进一步处理。

I bought a device and I installed its driver. 我买了一台设备,然后安装了它的驱动程序。 The only way for me to obtain its data is using command line in command prompt. 我获取数据的唯一方法是在命令提示符下使用命令行。 There is no API available. 没有可用的API。 But, I want to do in c# so that is why I am having trouble. 但是,我想用c#做,所以这就是我遇到麻烦的原因。

I have some code and it doesn't works for some reason. 我有一些代码,但由于某种原因它不起作用。 Note, I used argument input = "date" is only for illustration purpose. 注意,我使用的参数input =“date”仅用于说明目的。 My work is not using "date" but some arguments to obtain data. 我的工作不是使用“日期”,而是使用一些参数来获取数据。

static void Main(string[] args)
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    // the cmd program
    startInfo.FileName = "cmd.exe";
    // set my arguments. date is just a dummy example. the real work isn't use date.
    startInfo.Arguments = "date";
    startInfo.RedirectStandardOutput = true;
    startInfo.UseShellExecute = false;
    process.StartInfo = startInfo;
    process.Start();
    // capture what is generated in command prompt
    var output = process.StandardOutput.ReadToEnd();
    // write output to console
    Console.WriteLine(output);
    process.WaitForExit();

    Console.Read();
}

Any help is appreciated. 任何帮助表示赞赏。

I would also guess not all applications use stderr and stdout properly so it is possible what you see in a "Console Application" is not delivering the information where you expect it. 我猜也不是所有的应用程序都能正确使用stderr和stdout,所以你在“控制台应用程序”中看到的信息可能无法提供你所期望的信息。

If nothing more redirecting stderr as well, will also allow you to see if it is syntax related and the application is tossing an exception. 如果没有更多重定向stderr,也将允许您查看它是否与语法相关并且应用程序正在抛出异常。

startInfo.RedirectStandardError = true;

I want to add to that, by wrapping it up in a class, you can interact with the cmd shell, not just run and return... If you are trying to automate an application silently, this is likely the approach you want... 我想补充一点,通过将其包装在一个类中,您可以与cmd shell进行交互,而不仅仅是运行并返回...如果您尝试静默自动化应用程序,这可能是您想要的方法。 。

I just wrote a sample of this for a guy in VB, the syntax is probably rough because I had not launched VB in years, but you get the gist of it and should be able to replicate in C# fairly easily. 我刚刚为VB中的一个人写了一个这样的例子,语法可能很粗糙,因为我多年没有启动过VB,但你得到了它的要点,应该能够很容易地在C#中复制。 This was a rough draft How to type approach, not a piece of code I would call production ready, teach a man to fish sample ;) 这是一个粗略的草案如何键入方法,而不是一段代码,我会称之为生产准备,教一个人钓鱼样本;)

#Region " Imports "

Imports System.Threading
Imports System.ComponentModel

#End Region

Namespace Common

    Public Class CmdShell

#Region " Variables "

        Private WithEvents ShellProcess As Process

#End Region

#Region " Events "

        ''' <summary>
        ''' Event indicating an asyc read of the command process's StdOut pipe has occured.
        ''' </summary>
        Public Event DataReceived As EventHandler(Of CmdShellDataReceivedEventArgs)

#End Region

#Region " Public Methods "

        Public Sub New()
            ThreadPool.QueueUserWorkItem(AddressOf ShellLoop, Nothing)
            Do Until Not ShellProcess Is Nothing : Loop
        End Sub

        ''' <param name="Value">String value to write to the StdIn pipe of the command process, (CRLF not required).</param>
        Public Sub Write(ByVal value As String)
            ShellProcess.StandardInput.WriteLine(value)
        End Sub

#End Region

#Region " Private Methods "

        Private Sub ShellLoop(ByVal state As Object)
            Try
                Dim SI As New ProcessStartInfo("cmd.exe")
                With SI
                    .Arguments = "/k"
                    .RedirectStandardInput = True
                    .RedirectStandardOutput = True
                    .RedirectStandardError = True
                    .UseShellExecute = False
                    .CreateNoWindow = True
                    .WorkingDirectory = Environ("windir")
                End With
                Try
                    ShellProcess = Process.Start(SI)
                    With ShellProcess
                        .BeginOutputReadLine()
                        .BeginErrorReadLine()
                        .WaitForExit()
                    End With
                Catch ex As Exception
                    With ex
                        Trace.WriteLine(.Message)
                        Trace.WriteLine(.Source)
                        Trace.WriteLine(.StackTrace)
                    End With
                End Try
            Catch ex As Exception
                With ex
                    Trace.WriteLine(.Message)
                    Trace.WriteLine(.Source)
                    Trace.WriteLine(.StackTrace)
                End With
            End Try
        End Sub

        Private Sub ShellProcess_ErrorDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles ShellProcess.ErrorDataReceived
            If Not e.Data Is Nothing Then RaiseEvent DataReceived(Me, New CmdShellDataReceivedEventArgs(e.Data))
        End Sub

        Private Sub ShellProcess_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles ShellProcess.OutputDataReceived
            If Not e.Data Is Nothing Then RaiseEvent DataReceived(Me, New CmdShellDataReceivedEventArgs(e.Data & Environment.NewLine))
        End Sub

#End Region

    End Class

    <EditorBrowsable(EditorBrowsableState.Never)> _
       Public Class CmdShellDataReceivedEventArgs : Inherits EventArgs
        Private _Value As String

        Public Sub New(ByVal value As String)
            _Value = value
        End Sub

        Public ReadOnly Property Value() As String
            Get
                Return _Value
            End Get
        End Property

    End Class

End Namespace

Just to make sure there were no pitfalls, I went ahead and did this dirty in c# 为了确保没有陷阱,我继续在c#做了这个脏

 public class cmdShell
    {
        private Process shellProcess;

        public delegate void onDataHandler(cmdShell sender, string e);
        public event onDataHandler onData;

        public cmdShell()
        {
            try
            {
                shellProcess = new Process();
                ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
                si.Arguments = "/k";
                si.RedirectStandardInput = true;
                si.RedirectStandardOutput = true;
                si.RedirectStandardError = true;
                si.UseShellExecute = false;
                si.CreateNoWindow = true;
                si.WorkingDirectory = Environment.GetEnvironmentVariable("windir");
                shellProcess.StartInfo = si;
                shellProcess.OutputDataReceived += shellProcess_OutputDataReceived;
                shellProcess.ErrorDataReceived += shellProcess_ErrorDataReceived;
                shellProcess.Start();
                shellProcess.BeginErrorReadLine();
                shellProcess.BeginOutputReadLine();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
        }

        void shellProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            doOnData(e.Data);
        }

        void shellProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            doOnData(e.Data);
        }

        private void doOnData(string data)
        {
            if (onData != null) onData(this, data);
        }

        public void write(string data)
        {
            try
            {
                shellProcess.StandardInput.WriteLine(data);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
        }
    }

So now using like this 所以现在使用这样的

cmdShell test = new cmdShell();
test.onData += test_onData;
test.write("ping 127.0.0.1");

with this on place 随着这个

 void test_onData(cmdShell sender, string e)
        {
            Trace.WriteLine(e);
        }

You have a fully interactive cmd process to write to and receive async data from. 您有一个完全交互式的cmd进程来写入和接收异步数据。

outputs to the window 输出到窗口

C:\Windows>ping 127.0.0.1

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

Coffee, sleep... lol 咖啡,睡觉......哈哈

If you really want date... 如果你真的想约会...

cmdShell test = new cmdShell();
test.onData += test_onData;
test.write("date");

Yields output 产量

C:\Windows>date
The current date is: Wed 10/08/2014

or 要么

    cmdShell test = new cmdShell();
    test.onData += test_onData;
    test.write("echo %date%");

Yields output 产量

C:\Windows>echo %date%
Wed 10/08/2014

By the way, in case you have not actually used the code yet, this method gives the data async, meaning as the program outputs it is delivered to you, so if you run a process that takes time, like 100 pings, traceroute, etc... you see them as they happen, not have to wait for it to complete and return. 顺便说一句,如果你还没有实际使用的代码呢,这个方法给出了数据异步,这意味着在递送到你的程序的输出,所以如果你运行一个过程,需要时间,像100坪,路由跟踪等......你看到它们发生的时候,不必等待它完成并返回。

Also you can pass commands back to the application during that, like canceling, reacting to and changing syntax, or simply running something else similar based on the result of the first run. 此外,您可以在此期间将命令传递回应用程序,例如取消,响应和更改语法,或者根据第一次运行的结果运行其他类似的操作。

essentially you can treat it just like you were typing in a cmd window, and receiving the feedback there, wrap the whole think in a properly threaded form (Careful when updating windows controls from other threads), and you would have an emulated cmd prompt. 基本上你可以像在cmd窗口中输入一样对待它,并在那里接收反馈,以正确的线程形式包装整个思考(从其他线程更新Windows控件时小心),你会有一个模拟的cmd提示符。

you'll need to use /c date to get cmd to launch date like that. 你需要使用/ c date来让cmd像那样启动日期。

static void Main(string[] args)
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    // the cmd program
    startInfo.FileName = "cmd.exe";
    // set my arguments. date is just a dummy example. the real work isn't use date.
    startInfo.Arguments = "/c date";
    startInfo.RedirectStandardOutput = true;
    startInfo.UseShellExecute = false;
    process.StartInfo = startInfo;
    process.Start();
    // capture what is generated in command prompt
    var output = process.StandardOutput.ReadToEnd();
    // write output to console
    Console.WriteLine(output);
    process.WaitForExit();

    Console.Read();
}

the flags /c and /k are your friends when using cmd.exe to launch other programs. 使用cmd.exe启动其他程序时,flags / c和/ k是您的朋友。 /c is used to execute a program then exit CMD. / c用于执行程序然后退出CMD。 /k is used to execute a program then leave CMD running. / k用于执行程序,然后让CMD运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM