執行 鏈接 下載 ...
執行
public static void Run() { var state = ConnectState(@"\\192.168.10.160\excel\", "fish", "12345"); if (state) { // 共用文件夾的目錄 TransportRemoteToLocal(@"\\192.168.10.160\excel\1ff79391090d4e8fa507ada85bae31ec.xlsx", @"D:\Fish-a1.xlsx"); } }
鏈接
/// <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="saveSrc">保存到本地的路徑:下載到本地後的文件路徑,包含文件的擴展名</param> /// <param name="sourceSrc">遠程伺服器路徑(共用文件夾路徑)+ 遠程伺服器(共用文件夾)中的文件名稱,包含擴展名</param> public static void TransportRemoteToLocal(string sourceSrc, string saveSrc) { // 遠程伺服器文件 此處假定遠程伺服器共用文件夾下確實包含本文件,否則程式報錯 if (!File.Exists(sourceSrc)) return; FileStream inFileStream = File.OpenRead(sourceSrc); // 從遠程伺服器下載到本地的文件 FileStream outFileStream = new FileStream(saveSrc, 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(); }