C#讀寫共享資料夾
阿新 • • 發佈:2020-12-15
1、在伺服器設定一個共享資料夾,在這裡我的伺服器ip地址是10.200.8.73,共享資料夾名字是share,訪問許可權,使用者名稱是administrator,密碼是11111111。
2、新建一個控制檯專案。
3、新增後臺程式碼如下:
class Program { static void Main(string[] args) { bool status = false; //連線共享資料夾 status = connectState(@"\\10.200.8.73\share", "administrator", "11111111"); if (status) { //共享資料夾的目錄 DirectoryInfo theFolder = new DirectoryInfo(@"\\10.200.8.73\share"); //相對共享資料夾的路徑 string fielpath=@"\123\456\"; //獲取儲存檔案的路徑 string filename = theFolder.ToString() +fielpath ;//執行方法 Transport(@"D:\1.jpg", filename, "1.jpg"); } else { //ListBox1.Items.Add("未能連線!"); } Console.ReadKey(); } public static bool connectState(string path) { return connectState(path, "", ""); } /// <summary> /// 連線遠端共享資料夾 /// </summary> /// <param name="path">遠端共享資料夾的路徑</param> /// <param name="userName">使用者名稱</param> /// <param name="passWord">密碼</param> /// <returns></returns> public static bool connectState(string path, string userName, string passWord) { bool Flag = false; Process proc = new Process(); try { proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); string dosLine = "net use " + path + " " + passWord + " /user:" + userName; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(1000); } string errormsg = proc.StandardError.ReadToEnd(); proc.StandardError.Close(); if (string.IsNullOrEmpty(errormsg)) { Flag = true; } else { throw new Exception(errormsg); } } catch (Exception ex) { throw ex; } finally { proc.Close(); proc.Dispose(); } return Flag; } /// <summary> /// 向遠端資料夾儲存本地內容,或者從遠端資料夾下載檔案到本地 /// </summary> /// <param name="src">要儲存的檔案的路徑,如果儲存檔案到共享資料夾,這個路徑就是本地檔案路徑如:@"D:\1.avi"</param> /// <param name="dst">儲存檔案的路徑,不含名稱及副檔名</param> /// <param name="fileName">儲存檔案的名稱以及副檔名</param> public static void Transport(string src, string dst,string fileName) { FileStream inFileStream = new FileStream(src, FileMode.Open); if (!Directory.Exists(dst)) { Directory.CreateDirectory(dst); } dst = dst + fileName; FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate); byte[] buf = new byte[inFileStream.Length]; int byteCount; while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0) { outFileStream.Write(buf, 0, byteCount); } inFileStream.Flush(); inFileStream.Close(); outFileStream.Flush(); outFileStream.Close(); } }