Tom*_*rop 10 .net c# command-line process
我正在编写一个运行任意命令所需的简单应用程序,例如:
powershell -File myscript.ps1
cmd /C "ping localhost"
Run Code Online (Sandbox Code Playgroud)
Process.Start()将是完美的,除非它要求将参数作为单独的参数给出.最初我以为我可以在第一个空格字符上拆分字符串,但是如果引用可执行路径并包含空格怎么办?是否有类似Process.Start()的东西允许你只给它一个字符串,有或没有参数,只是让它执行它就好像它被粘贴到命令提示符一样?
只需CreateProcess直接调用该函数:
public static class Native
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
public static void CreateProcessFromCommandLine(string commandLine)
{
var si = new STARTUPINFO();
var pi = new PROCESS_INFORMATION();
CreateProcess(
null,
commandLine,
IntPtr.Zero,
IntPtr.Zero,
false,
0,
IntPtr.Zero,
null,
ref si,
out pi);
}
}
internal class Program
{
public static void Main()
{
Native.CreateProcessFromCommandLine("ping google.com -t");
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
296 次 |
| 最近记录: |