專案需以程式碼建立網路共享,採用 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 方式建立共享,避免命令列解析問題。
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);
}