Cmd重定向

来源:https://www.cnblogs.com/publiter/archive/2020/07/14/13298468.html
-Advertisement-
Play Games

1、執行單條cmd命令public static string ExecuteCmd(string command) { Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute ...


1、執行單條cmd命令

public static string ExecuteCmd(string command)
{
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;    //是否使用操作系統shell啟動
    p.StartInfo.RedirectStandardInput = true;//接受來自調用程式的輸入信息
    p.StartInfo.RedirectStandardOutput = true;//由調用程式獲取輸出信息
    p.StartInfo.RedirectStandardError = true;//重定向標準錯誤輸出
    p.StartInfo.CreateNoWindow = true;//不顯示程式視窗
    //p.StartInfo.Arguments = "/c " + command;///c代表執行命令後關閉cmd.exe /k參數則不關閉
    p.Start();//啟動程式
    //消除三行啟動信息
    p.StandardOutput.ReadLine();
    p.StandardOutput.ReadLine();
    p.StandardOutput.ReadLine();
    //向cmd視窗發送輸入信息
    p.StandardInput.WriteLine(command);
    p.StandardInput.WriteLine("exit");
    string result = p.StandardOutput.ReadToEnd().Replace(Environment.CurrentDirectory, "");
    string error = p.StandardError.ReadToEnd();
    if (!string.IsNullOrWhiteSpace(error))
        result = result + "\r\n<Error Message>:\r\n" + error;
    p.WaitForExit();
    p.Close();
    return result;
}

2、一次執行多條cmd命令

public static string ExecuteCmd(string[] commands)
{
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;    //是否使用操作系統shell啟動
    p.StartInfo.RedirectStandardInput = true;//接受來自調用程式的輸入信息
    p.StartInfo.RedirectStandardOutput = true;//由調用程式獲取輸出信息
    p.StartInfo.RedirectStandardError = true;//重定向標準錯誤輸出
    p.StartInfo.CreateNoWindow = true;//不顯示程式視窗
    //p.StandardInput.AutoFlush = true;//每次寫入命令後刷新,報未StandardInput未重定向
    //p.StartInfo.Arguments = "/c " + command;///c代表執行命令後關閉cmd.exe /k參數則不關閉
    p.Start();//啟動程式
    //消除三行啟動信息
    p.StandardOutput.ReadLine();
    p.StandardOutput.ReadLine();
    p.StandardOutput.ReadLine();

    //向cmd視窗發送輸入信息
    foreach (string cmd in commands)
    {
        p.StandardInput.WriteLine(cmd);
        p.StandardInput.Flush();
    }
    p.StandardInput.WriteLine("exit");
    string result = p.StandardOutput.ReadToEnd().Replace(Environment.CurrentDirectory, "");
    string error = p.StandardError.ReadToEnd();
    if (!string.IsNullOrWhiteSpace(error))
        result = result + "\r\n<Error Message>:\r\n" + error;
    p.WaitForExit();
    p.Close();

    return result;
}

3、利用cmd重定向註冊DLL、創建服務、載入證書

public static string RegsvrFile(string filePath, bool reg = true, bool fileBit64 = false)
{
    string result;
    string[] commands = { "", "" };
    if (!fileBit64 && Environment.Is64BitOperatingSystem)
        commands[0] = "cd /d %WinDir%\\SysWOW64";
    if (reg)
        commands[1] = "regsvr32 /s \"" + filePath + "\"";
    else
        commands[1] = "regsvr32 /u /s \"" + filePath + "\"";
    if (string.IsNullOrWhiteSpace(commands[0]))
        result = CmdOper.ExecuteCmd(commands[1]);
    else
        result = CmdOper.ExecuteCmd(commands);
    return result;
}

public static string ScCreate(string filePath, string serviceName, string displayName, string description, string start="auto", string depend=null)
{
    string result;
    string[] commands = { "", "" };
    if (string.IsNullOrWhiteSpace(depend))
    {
        commands[0] = string.Format("sc create {0} binPath= \"{1}\" type= share start= {2} error= ignore DisplayName= \"{3}\"",
            serviceName, filePath, start, displayName);
    }
    else
    {
        commands[0] = string.Format("sc create {0} binPath= \"{1}\" type= share start= {2} error= ignore DisplayName= \"{3}\" depend= {4}",
            serviceName, filePath, start, displayName, depend);
    }
    if (!string.IsNullOrWhiteSpace(description))
    {
        commands[1] = string.Format("sc description {0} \"{1}\"", serviceName, description);
    }
    if (string.IsNullOrWhiteSpace(commands[1]))
        result = CmdOper.ExecuteCmd(commands[0]);
    else
        result = CmdOper.ExecuteCmd(commands);

    return result;
}

public static string ScStart(string serviceName)
{
    string command = "net start " + serviceName;
    return CmdOper.ExecuteCmd(command);
}

public static string ScStop(string serviceName)
{
    string command = "net stop " + serviceName;
    return CmdOper.ExecuteCmd(command);
}

public static string ScDelete(string serviceName)
{
    string[] commands = { "net stop " + serviceName, "sc delete " + serviceName };
    return CmdOper.ExecuteCmd(commands);
}

public static string CertFile(string filePath, bool install=true)
{
    string result;
    string[] commands = { "", "" };
    if (Environment.Is64BitOperatingSystem)
        commands[0] = "cd /d %WinDir%\\SysWOW64";
    if (install)
        commands[1] = "certutil -addstore root \"" + filePath + "\"";
    else
        commands[1] = "certutil -delstore root \"" + filePath + "\"";
    if (string.IsNullOrWhiteSpace(commands[0]))
        result = CmdOper.ExecuteCmd(commands[1]);
    else
        result = CmdOper.ExecuteCmd(commands);
    return result;
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 如果你正處於學Python狀態,或者是已經在學Python的小伙伴,下麵這些資料是一套Python入門視頻教程,也有電子書,現在免費分享出來提供學習 ...
  • 主席樹的一點點學習體會,主席樹是一種可持久化的數據結構,第一次這麼深入的學習可持久化的數據結構,花了好幾天學習它包括他的前置知識嗚噫嗚噫~,主要是寫給兩個可愛的隊友看的,歡迎各位批評指正! ...
  • maven多項目啟動 在多項目的maven項目里,你可以通過配置.idea/workspace.xml來配置多項目同時啟動,這樣方便於你的調試,不需要一個一個的啟動了 workspace.xml文件里添加 <component name="RunDashboard"> <option name="c ...
  • 1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <configSections> 4 <section name="log4net" type="log4net.Config.Log4NetConfigurationSect ...
  • 最近才接觸js的模板引擎聽說相比以前使用的js foreach載入後臺返回的json數據簡便很多而且效率方面也很不錯。今天自己玩了一下 後臺使用的是.net mvc,資料庫腳本就不提供了,返回的JsonResult,將數據存放在data中,前臺通過ajax配合模板引擎進行一個調用然後以表格的形式顯示 ...
  • 介面與抽象類的區別: 介面支持多繼承;抽象類不能實現多繼承。 介面可以用於支持回調;抽象類不能實現回調,因為繼承不支持。 介面只包含方法、屬性、索引器、事件的簽名,但不能定義欄位和包含實現的方法;抽象類可以定義欄位、屬性、包含有實現的方法。 介面可以作用於值類型和引用類型;抽象類只能作用於引用類型。 ...
  • 一、前言 在之前的使用Swagger做Api文檔中,我們已經使用Swagger進行開發介面文檔,以及更加方便的使用。這一轉換,讓更多的介面可以以通俗易懂的方式展現給開發人員。而在後續的內容中,為了對api資源的保護,我們引入了認證授權方案,利用HTTP提供了一套標準的身份驗證框架,服務端可以用來針對 ...
  • 首先,要知道.Net Core和.Net Framework兩個環境下很多東西是不同的,接下來要說的這個就是其中一個。 Encoding.Default,在 .NET Framework 中,Default屬性始終獲取系統的活動代碼頁,並創建對應於它的 Encoding對象。 而在 .NET Cor ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...