C# Form中调用外部DOS命令

.net提供了强大的功能来调用外部工具,并通过重定向输入、输出获取执行结果。

下面就用一个例子来说明调用Ping.exe命令实现网络的检测。

首先,用使用Process类,来创建独立的进程,导入System.Diagnostics,

using System.Diagnostics;

实例一个Process类,启动一个独立进程

Process p = new Process();

Process类有一个StartInfo属性,这个是ProcessStartInfo类,包括了一些属性和方法,

下面我们用到了他的几个属性:

设定程序名

p.StartInfo.FileName = "cmd.exe";

关闭Shell的使用

p.StartInfo.UseShellExecute = false;

重定向标准输入

p.StartInfo.RedirectStandardInput = true;

重定向标准输出

p.StartInfo.RedirectStandardOutput = true;

重定向错误输出

p.StartInfo.RedirectStandardError = true;

设置不显示窗口

p.StartInfo.CreateNoWindow = true;

上面几个属性的设置是比较关键的一步。

既然都设置好了那就启动进程吧,

p.Start();

输入要执行的命令,这里就是ping了,

p.StandardInput.WriteLine("ping -n 1 192.192.132.229");

p.StandardInput.WriteLine("exit");

从输出流获取命令执行结果,

string strRst = p.StandardOutput.ReadToEnd();

在本机测试得到如下结果:

"Microsoft Windows 2000 [Version 5.00.2195]/r/n(C) 版权所有 1985-2000 Microsoft Corp./r/n/r/nD://himuraz//csharpproject//ZZ//ConsoleTest//bin//Debug>ping -n 1 192.192.132.231/r/n/r/r/nPinging 192.192.132.231 with 32 bytes of data:/r/r/n/r/r/nReply from 192.192.132.231: bytes=32 time<10ms TTL=128/r/r/n/r/r/nPing statistics for 192.192.132.231:/r/r/n Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),/r/r/nApproximate round trip times in milli-seconds:/r/r/n Minimum = 0ms, Maximum = 0ms, Average = 0ms/r/r/n/r/nD://himuraz//csharpproject//ZZ//ConsoleTest//bin//Debug>exit/r/n"

有了输出结果,那还有什么好说的,分析strRst字符串就可以知道网络的连接情况了。

下面是一个完整的程序,当然对Ping.exe程序执行的结果不全,可以进一步修改。


完整代码如下:

using  System;
using  System.Diagnostics;

namespace  ZZ
{
    
class  ZZConsole
    {
        [STAThread]
        
static   void  Main( string [] args)
        { 
            
string  ip  =   " 192.192.132.229 " ;
            
string  strRst  =  CmdPing(ip);
            Console.WriteLine(strRst);
            Console.ReadLine();
        }
        
private   static   string  CmdPing( string  strIp)
        {
            Process p 
=   new  Process();
            p.StartInfo.FileName 
=   " cmd.exe " ;
            p.StartInfo.UseShellExecute 
=   false ;
            p.StartInfo.RedirectStandardInput 
=   true ;
            p.StartInfo.RedirectStandardOutput 
=   true ;
            p.StartInfo.RedirectStandardError 
=   true ;
            p.StartInfo.CreateNoWindow 
=   true ;

            
string  pingrst;
            p.Start();
            p.StandardInput.WriteLine(
" ping -n 1  " + strIp);
            p.StandardInput.WriteLine(
" exit " );

            
string  strRst  =  p.StandardOutput.ReadToEnd();
            
if (strRst.IndexOf( " (0% loss) " ) !=- 1 )
            pingrst 
=   " 连接 " ;
            
else   if ( strRst.IndexOf( " Destination host unreachable. " ) !=- 1 )
                pingrst 
=   " 无法到达目的主机 " ;
            
else   if (strRst.IndexOf( " Request timed out. " ) !=- 1 )
                pingrst 
=   " 超时 " ;
            
else   if (strRst.IndexOf( " Unknown host " ) !=- 1 )
                pingrst 
=   " 无法解析主机 " ;
            
else
                pingrst 
=  strRst;
            p.Close();
            
return  pingrst;
        }
    }
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]提供了一个C#的HttpPost方法,用于向指定的URL发送POST请求,并返回请求结果。在使用该方法前,需要确保已经引入了System.Net.Http命名空间。 要在C#Form1使用该方法,可以按照以下步骤进行操作: 1. 在Form1类添加一个方法,例如`SendHttpPostRequest`,用于调用HttpPost方法发送POST请求。 2. 在该方法,根据需要设置URL和JSON数据,并调用HttpPost方法发送请求。 3. 处理HttpPost方法的返回结果,可以将结果显示在Form1的界面上,或者进行其他操作。 下面是一个示例代码,演示了如何在Form1使用HttpPost方法发送POST请求: ```csharp using System; using System.Windows.Forms; using System.Net.Http; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void SendHttpPostRequest() { string url = "http://example.com/api"; // 设置请求的URL string json = "{\"key\": \"value\"}"; // 设置请求的JSON数据 try { string result = HttpPost(url, json); // 调用HttpPost方法发送POST请求 // 处理请求结果,例如将结果显示在界面上 MessageBox.Show(result); } catch (Exception ex) { MessageBox.Show("请求异常:" + ex.Message); } } private string HttpPost(string url, string json) { string content = ""; try { // 构造请求内容 var mfdc = new MultipartFormDataContent(); mfdc.Headers.Add("ContentType", "multipart/form-data"); // 添加参数 mfdc.Add(new StringContent(json), "data"); // 发起请求 var clientTask = new HttpClient().PostAsync(url, mfdc); clientTask.Wait(); // 处理请求结果 if (clientTask.Result.IsSuccessStatusCode) { var resultTask = clientTask.Result.Content.ReadAsStringAsync(); resultTask.Wait(); content = resultTask.Result; } else { content = "请求失败"; } } catch (Exception ex) { content = ex.Message; } return content; } private void button1_Click(object sender, EventArgs e) { SendHttpPostRequest(); } } ``` 在上述示例代码,我们在Form1类添加了一个按钮和一个点击事件处理方法`button1_Click`,当点击按钮时,会调用`SendHttpPostRequest`方法发送POST请求,并将请求结果显示在消息框。你可以根据实际需求进行修改和扩展。 #### 引用[.reference_title] - *1* [c#HTTP使用form-data发送请求](https://blog.csdn.net/qq285503851/article/details/127441224)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值