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(); } } View Code按以上步驟,即可實現讀寫網絡共享文件。