Skip to content

Commit

Permalink
[feat]新增StringHelper.Execute,执行命令并等待返回
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Jul 19, 2024
1 parent a5ea464 commit 4f72c07
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 37 deletions.
39 changes: 4 additions & 35 deletions NewLife.Core/Common/MachineInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ private void LoadWindowsInfo()
}
}
#else
str = Execute("reg", @"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid");
str = "reg".Execute(@"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid", 0, false);
if (!str.IsNullOrEmpty() && str.Contains("REG_SZ")) Guid = str.Substring("REG_SZ", null).Trim();

var csproduct = ReadWmic("csproduct", "Name", "UUID", "Vendor");
Expand Down Expand Up @@ -825,7 +825,7 @@ public void RefreshSpeed()
var sr = "/etc/os-release";
if (TryRead(sr, out value)) return value?.SplitAsDictionary("=", "\n", true)["PRETTY_NAME"].Trim();

var uname = Execute("uname", "-sr")?.Trim();
var uname = "uname".Execute("-sr", 0, false)?.Trim();
if (!uname.IsNullOrEmpty())
{
// 支持Android系统名
Expand Down Expand Up @@ -906,40 +906,9 @@ private static Boolean TryRead(String fileName, [NotNullWhen(true)] out String?
return dic;
}

private static String? Execute(String cmd, String? arguments = null)
{
try
{
#if DEBUG
if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Execute({0} {1})", cmd, arguments);
#endif

var psi = new ProcessStartInfo(cmd, arguments ?? String.Empty)
{
// UseShellExecute 必须 false,以便于后续重定向输出流
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
//RedirectStandardError = true,
};
var process = Process.Start(psi);
if (process == null) return null;

if (!process.WaitForExit(3_000))
{
process.Kill();
return null;
}

return process.StandardOutput.ReadToEnd();
}
catch { return null; }
}

private static IDictionary<String, String>? ReadCommand(String cmd, String? arguments = null)
{
var str = Execute(cmd, arguments);
var str = cmd.Execute(arguments, 0, false);
if (str.IsNullOrEmpty()) return null;

return str.SplitAsDictionary(":", "\n", true);
Expand All @@ -955,7 +924,7 @@ private static Boolean TryRead(String fileName, [NotNullWhen(true)] out String?
var dic2 = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase);

var args = $"{type} get {keys.Join(",")} /format:list";
var str = Execute("wmic", args)?.Trim();
var str = "wmic".Execute(args, 0, false)?.Trim();
if (str.IsNullOrEmpty()) return dic2;

var ss = str.Split("\r\n");
Expand Down
43 changes: 41 additions & 2 deletions NewLife.Core/Extension/StringHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -980,7 +980,7 @@ public static String SpeakAsyncCancelAll(this String value)
/// <returns>进程退出代码</returns>
public static Int32 Run(this String cmd, String? arguments = null, Int32 msWait = 0, Action<String?>? output = null, Action<Process>? onExit = null, String? working = null)
{
if (XTrace.Debug) XTrace.WriteLine("Run {0} {1} {2}", cmd, arguments, msWait);
if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Run {0} {1} {2}", cmd, arguments, msWait);

// 修正文件路径
var fileName = cmd;
Expand Down Expand Up @@ -1039,7 +1039,7 @@ public static Int32 Run(this String cmd, String? arguments = null, Int32 msWait
/// <returns></returns>
public static Process ShellExecute(this String fileName, String? arguments = null, String? workingDirectory = null)
{
if (XTrace.Debug) XTrace.WriteLine("ShellExecute {0} {1} {2}", fileName, arguments, workingDirectory);
if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("ShellExecute {0} {1} {2}", fileName, arguments, workingDirectory);

//// 修正文件路径
//if (!Path.IsPathRooted(fileName) && !workingDirectory.IsNullOrEmpty()) fileName = workingDirectory.CombinePath(fileName);
Expand All @@ -1055,5 +1055,44 @@ public static Process ShellExecute(this String fileName, String? arguments = nul

return p;
}

/// <summary>执行命令并等待返回</summary>
/// <param name="cmd">命令</param>
/// <param name="arguments">命令参数</param>
/// <param name="msWait">等待退出的时间。默认0毫秒不等待</param>
/// <param name="returnError">没有标准输出时,是否返回错误内容。默认false</param>
/// <returns></returns>
public static String? Execute(this String cmd, String? arguments = null, Int32 msWait = 0, Boolean returnError = false)
{
try
{
if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Execute {0} {1}", cmd, arguments);

var psi = new ProcessStartInfo(cmd, arguments ?? String.Empty)
{
// UseShellExecute 必须 false,以便于后续重定向输出流
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
//RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8,
};
var process = Process.Start(psi);
if (process == null) return null;

if (msWait > 0 && !process.WaitForExit(msWait))
{
process.Kill();
return null;
}

var rs = process.StandardOutput.ReadToEnd();
if (rs.IsNullOrEmpty() && returnError) rs = process.StandardError.ReadToEnd();

return rs;
}
catch { return null; }
}
#endregion
}

0 comments on commit 4f72c07

Please sign in to comment.