以下代码可以实现将远程主机上的共享文件复制到本地。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace FileCopyFromRemoteComputer
{
class Program
{
static void Main(string[] args)
{
if (Ping("10.71.1.67"))
{
string remote = @"\\10.71.1.67\gongxiang222";
string aimPath = @"D:\copytest";
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) //给目标路径添加\\
aimPath += Path.DirectorySeparatorChar;
if (!Directory.Exists(aimPath))
//如果目标文件夹不存在,则创建
Directory.CreateDirectory(aimPath);
string[] fileList = Directory.GetFileSystemEntries(remote);
//获取远程路径下的所有文件列表
DateTime dtStart = DateTime.Now;
//开始复制的时间
foreach (string file in fileList)
{
File.Copy(file, aimPath + Path.GetFileName(file), true);
//复制文件到目标路径
}
DateTime dtEnd = DateTime.Now;
//结束时间
int time = dtEnd.Subtract(dtStart).Seconds;
//耗时统计
Console.WriteLine(time);
Console.ReadKey();
}
}
public static bool Ping(string remoteHost)
//Ping远程主机
{
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;
}
}
}