C#技术百科
问问你的心你有没有信心 做事情要专一坚定,执着

使用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);
    }
   }

posted on 2010-07-27 22:29  王德田  阅读(2278)  评论(0编辑  收藏  举报