.NET 创建、读取和写入进程类

创建进程的示例以及如何使用 System.Diagnostics.Process 类读取控制台输出并写入控制台以及如何使用 Windows 管理规范 (WMI) 在远程计算机上创建进程;用 C# 和 VB.NET 编写。

在.NET中创建一个新进程,Process.Start("notepad.exe")通过创建对象可以实现简单但更多的控制Process。Process.Start("http://www.bing.com")也可以。可能,Process.Start()正在使用WinAPI ShellExecute()函数,而Process对象正在使用该CreateProcess()函数(至少对于 Windows 平台而言)。

了解如何使用 HttpClient从 URL 下载文件终止进程

VB.NET

Imports System.Diagnostics

Module Module1

Sub Main()

Dim pro As New Process()

pro.StartInfo.FileName = "notepad.exe"

pro.StartInfo.Arguments = "temp.txt"

' NOTE: can specify ProcessWindowStyle.Hidden for programs that do not need user input

pro.StartInfo.WindowStyle = ProcessWindowStyle.Normal

pro.Start()

pro.WaitForExit()

End Sub

End Module

C#:

using System.Diagnostics;

namespace Console1

{

class Program

{

static void Main(string[] args)

{

Process pro = new Process();

pro.StartInfo.FileName = "notepad.exe";

pro.StartInfo.Arguments = "temp.txt";

// NOTE: can specify ProcessWindowStyle.Hidden for programs that do not need user input

pro.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

pro.Start();

pro.WaitForExit();

}

}

}

读取控制台应用程序输出

创建一个控制台进程并读取其输出。

using (var proc = new System.Diagnostics.Process

{

StartInfo = new System.Diagnostics.ProcessStartInfo

{

FileName = "/bin/executable",

Arguments = "-arguments",

UseShellExecute = false,

RedirectStandardOutput = true,

CreateNoWindow = true

}

})

{

proc.Start();

while (!proc.StandardOutput.EndOfStream)

{

// NOTE: can also read one character at a time with proc.StandardOutput.Read() for more of a "real-time" effect

string line = proc.StandardOutput.ReadLine();

// NOTE: do something with this line of text

}

}

现在,从控制台进程读取二进制数据。

using (var proc = new System.Diagnostics.Process

{

StartInfo = new System.Diagnostics.ProcessStartInfo

{

FileName = "/bin/executable",

Arguments = "-arguments",

UseShellExecute = false,

RedirectStandardOutput = true,

CreateNoWindow = true

}

})

{

proc.Start();

using (BinaryReader reader = new BinaryReader(proc.StandardOutput.BaseStream))

{

byte[] chunk = reader.ReadBytes(1024);

while (chunk.Length > 0)

{

// NOTE: do something with this byte array

chunk = reader.ReadBytes(1024);

}

}

}

写入控制台应用程序

实际上,如果对控制台应用程序进行读取和写入,则可能在不同的线程上进行,同样,控制台应用程序也可能在不同的线程上进行读取和写入。这是因为Console.ReadLine()、proc.StandardOutput.Read()和proc.StandardOutput.ReadLine()是阻塞的。

using (var proc = new System.Diagnostics.Process

{

StartInfo = new System.Diagnostics.ProcessStartInfo

{

FileName = Path.Combine(Environment.CurrentDirectory, "executable.exe"),

Arguments = "/command /line /arguments /go /here",

UseShellExecute = false,

RedirectStandardOutput = true, // NOTE: optional

RedirectStandardInput = true, // NOTE: required

CreateNoWindow = true, // NOTE: optional

WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden // NOTE: optional

}

})

{

proc.StandardInput.WriteLine("Hello, World!"); // NOTE: this will send "Hello, World!" to the console application's process

proc.StandardOutput.ReadLine();

}

在远程机器上创建进程

可以从 C# 应用程序远程在另一台计算机上创建进程,但这需要满足有关网络配置、权限和安全设置的特定条件。实现此目的的方法通常涉及使用 Windows 管理规范 (WMI)、PowerShell 远程处理或支持远程命令执行的其他网络协议。

Windows 管理规范 (WMI) 是一项 Windows 功能,它提供了一种与系统管理数据和操作进行交互的标准化方法。使用 WMI 在远程计算机上创建进程,但要确保本地计算机和远程计算机都配置为允许 WMI 访问。

using System;

using System.Management;

class Program

{

static void Main()

{

string remoteComputer = "REMOTE_COMPUTER_NAME";

string domain = "DOMAIN_NAME"; // NOTE: can be an empty string if not on a domain

string username = "USERNAME";

string password = "PASSWORD";

string processToRun = @"C:\Path\To\Executable.exe /command-line-argument";

ConnectionOptions connOptions = new ConnectionOptions();

connOptions.Username = domain + "\\" + username;

connOptions.Password = password;

connOptions.Impersonation = ImpersonationLevel.Impersonate;

connOptions.EnablePrivileges = true;

ManagementScope manScope = new ManagementScope($@"\\{remoteComputer}\root\cimv2", connOptions);

try

{

manScope.Connect();

ObjectGetOptions objectGetOptions = new ObjectGetOptions();

ManagementPath managementPath = new ManagementPath("Win32_Process");

ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);

ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

inParams["CommandLine"] = processToRun;

ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

Console.WriteLine("Return Value: " + outParams["ReturnValue"]); // NOTE: return value of 0 means success, just like with any regular process

}

catch (Exception e)

{

Console.WriteLine("Error: " + e.Message);

}

}

}

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
.NET修仙日记4 小时前
C#/.NET 微服务架构:从入门到精通的完整学习路线
微服务·c#·.net·.net core·分布式架构·技术进阶
追逐时光者18 小时前
全面的 C#/.NET 图表构建解决方案,助力快速实现图表开发需求!
后端·.net
唐青枫1 天前
C#.NET ArrayPool 深入解析:高性能内存池的实现与应用
c#·.net
一个专注写bug的小白猿2 天前
.net实现ftp传输文件保姆教程
后端·c#·.net
初级代码游戏2 天前
winform迁移:从.net framework 到 .net9
.net·迁移·.net framework
TeamDev2 天前
使用 Shadcn UI 构建 C# 桌面应用
前端·后端·.net
CodeCraft Studio2 天前
CADSoftTools发布两款重要更新:CAD VCL Multiplatform 16.2 与 CAD .NET 16全新发布
.net·cad vcl·cad .net·cad文件格式解析·cad文件编辑·cad文件查看器
唐青枫2 天前
C#.NET FluentSqlKata 全面解析:基于链式语法的动态 SQL 构建
c#·.net
用户298698530143 天前
Spire.Doc 实践指南:将Word 文档转换为 XML
后端·.net
忧郁的蛋~3 天前
.NET实现多任务异步与并行处理的详细步骤
后端·c#·asp.net·.net·.netcore