局域網共享文件夾需要用戶名和密碼才能訪問,通過程序怎樣才能獲得文件夾訪問權限呢?
這里主要利用了DOS命令中的“NET USE”命令來實現。
public static void GetAccessControl(string path,string user,string pwd) { Process p = new Process(); p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec"); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine(@"Net Use {0} /del", path); //必須先刪除,否則報錯 p.StandardInput.WriteLine(@"Net Use {0} ""{1}"" /user:{2}", path, pwd, user); p.StandardInput.WriteLine("exit"); //如果不加這句WaitForExit會卡住 p.WaitForExit(); p.Close(); }
如果大家還有更好的方法,歡迎指教哦