C# 远程拷贝文件

别等时光非礼了梦想. 提交于 2020-01-08 03:57:03

使用net use 命令实现远程机器的文件复制。
比如,从机器A操作实现把机器B的文件拷贝到机器A上,需要把机器B文件夹加上机器A的用户权限。

public static bool Ping(string remoteHost)
  {
   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 = @"ping -n 1 " + remoteHost;
    proc.StandardInput.WriteLine(dosLine);
    proc.StandardInput.WriteLine("exit");
    while (proc.HasExited == false)
    {
     proc.WaitForExit(500);
    }
    string pingResult = proc.StandardOutput.ReadToEnd();
    if (pingResult.IndexOf("(0% loss)") != -1)
    {
     Flag = true;
    }
    proc.StandardOutput.Close() ;
   }
   catch (Exception ex)
   {
   }
   finally
   {
    try
    {
     proc.Close();
     proc.Dispose();
    }
    catch
    {
    }
   }
   return Flag;
  }

  public static bool Connect(string remoteHost, string userName, string passWord)
  {
   if(!Ping(remoteHost))
   {
    return false;
   }
   bool Flag = true;
   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 \\" + remoteHost + " " + passWord + " " + " /user:" + userName + ">NUL";
    proc.StandardInput.WriteLine(dosLine);
    proc.StandardInput.WriteLine("exit");
    while (proc.HasExited == false)
    {
     proc.WaitForExit(1000);
    }
    string errormsg = proc.StandardError.ReadToEnd();
    if (errormsg != "")
    {
     Flag = false;
    }
    proc.StandardError.Close() ;
   }
   catch (Exception ex)
   {
    Flag = false;
   }
   finally
   {
    try
    {
     proc.Close();
     proc.Dispose();
    }
    catch
    {
    }
   }
   return Flag;
  }
这两个方法是对机器B建立连接,连接成功后,用File.Copy就可以了
if (Ping("机器B"))
   {
    if (Connect("机器B","机器A用户","机器A用户访问密码"))
    {
     File.Copy("\\机器B\文件路径\文件名称","机器A存放文件完整路径",true);
    }
   }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!