首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 執行 net share 指令共享資料夾:路徑含空格導致失敗的解決方案

     編輯:關於C語言

情境

專案需以程式碼建立網路共享,採用 net share 指令:


var p = new Process {
    StartInfo = {
        FileName = "cmd",
        Arguments = $"/c net share {shareName}={sharePath}",
        WindowStyle = ProcessWindowStyle.Hidden,
        CreateNoWindow = true,
        UseShellExecute = false,
        RedirectStandardOutput = true
    }
};
p.Start(); p.WaitForExit();

開發測試正常,部署至 Program Files 目錄下失敗。

根因

sharePath 包含空格(如 C:\Program Files\MyApp\Data),命令列解析時被拆分為多個參數,導致 net share 語法錯誤。

解決:雙引號包裹路徑


Arguments = $"/c net share {shareName}=\"{sharePath}\""

產生指令:net share MyShare="C:\Program Files\MyApp\Data",正確識別完整路徑。

完善建議

  • 若 shareName 可能含空格,同樣加引號:\"{shareName}\"=\"{sharePath}\"。
  • 路徑以反斜線結尾時,引號內不可以 \ 結尾(會被視為跳脫字元),建議 sharePath.TrimEnd('\\')。
  • 考慮使用 System.Management (WMI) Win32_Share.Create 以純 .NET 方式建立共享,避免命令列解析問題。

WMI 替代方案範例


using System.Management;

public void CreateShare(string path, string name, string description)
{
    var mc = new ManagementClass("Win32_Share");
    var inParams = mc.GetMethodParameters("Create");
    inParams["Path"] = path;
    inParams["Name"] = name;
    inParams["Type"] = 0x0; // Disk Drive
    inParams["Description"] = description;
    mc.InvokeMethod("Create", inParams, null);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved