1. 程式人生 > >c# 設置和取消文件夾共享及執行Dos命令

c# 設置和取消文件夾共享及執行Dos命令

urn cati 如果 llc seo value close 輸出 dos命令

        /// <summary>
        /// 設置文件夾共享
        /// </summary>
        /// <param name="FolderPath">文件夾路徑</param>
        /// <param name="ShareName">共享名</param>
        /// <param name="Description">共享註釋</param>
        /// <returns></returns>
        public static
int ShareNetFolder(string FolderPath, string ShareName, string Description) { try { ManagementClass managementClass = new ManagementClass("Win32_Share"); // Create ManagementBaseObjects for in and out parameters ManagementBaseObject inParams = managementClass.GetMethodParameters("
Create"); ManagementBaseObject outParams; // Set the input parameters inParams["Description"] = Description; inParams["Name"] = ShareName; inParams["Path"] = FolderPath; inParams["Type"] = 0x0; // Disk Drive outParams = managementClass.InvokeMethod("
Create", inParams, null); // Check to see if the method invocation was successful if ((uint)(outParams.Properties["ReturnValue"].Value) != 0) { throw new Exception("Unable to share directory."); } //設置所有人可讀 DirectorySecurity fSec = new DirectorySecurity(); fSec.AddAccessRule(new FileSystemAccessRule(@"Everyone", FileSystemRights.FullControl, AccessControlType.Allow)); System.IO.Directory.SetAccessControl(FolderPath, fSec); } catch { return -1; } return 0; } /// <summary> /// 取消文件夾共享 /// </summary> /// <param name="ShareName">文件夾的共享名</param> /// <returns></returns> public static int CancelShareNetFolder(string ShareName) { try { SelectQuery selectQuery = new SelectQuery("Select * from Win32_Share Where Name = ‘" + ShareName + ""); ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery); foreach (ManagementObject mo in searcher.Get()) { mo.InvokeMethod("Delete", null, null); } } catch { return -1; } return 0; } /// <summary> /// 執行Dos命令並返回執行結果,默認2秒內執行完 /// /// net session /delete /y 刪除該計算機的所有會話(局域網服務器連接超最大數時刻執行) /// 如果是服務器部署了網站,刪除會話命令慎用 /// </summary> /// <param name="dosCommand">dos命令</param> /// <param name="milliseconds">最大執行秒數</param> /// <returns></returns> public static string Execute(string dosCommand, int milliseconds=2000) { string output = ""; //輸出字符串 if (dosCommand != null && dosCommand != "") { Process process = new Process(); //創建進程對象 ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe"; //設定需要執行的命令 startInfo.Arguments = "/C " + dosCommand; //設定參數,其中的“/C”表示執行完命令後馬上退出 startInfo.UseShellExecute = false; //不使用系統外殼程序啟動 startInfo.RedirectStandardInput = false; //不重定向輸入 startInfo.RedirectStandardOutput = true; //重定向輸出 startInfo.CreateNoWindow = true; //不創建窗口 process.StartInfo = startInfo; try { if (process.Start()) //開始進程 { if (milliseconds == 0) process.WaitForExit(); //這裏無限等待進程結束 else process.WaitForExit(milliseconds); //這裏等待進程結束,等待時間為指定的毫秒 output = process.StandardOutput.ReadToEnd();//讀取進程的輸出 } } catch { } finally { if (process != null) process.Close(); } } return output; }

c# 設置和取消文件夾共享及執行Dos命令