一、获取远程路径
public static string GetRemotePath(string ip, string localPath)
{
if (!localPath.Contains(":"))
{
LoggerUtil.Info($"{localPath}路径必须是全路径且是本地路径");
}
localPath = localPath.Replace(":", "$");
return $@"\\{ip}\{localPath}";
}
二、连接远程共享文件夹
private 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)
{
LoggerUtil.Error("CopyUtil:ConnectState", ex);
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
三、拷贝文件到目标目录
public static void CopyFiles(string sourceFolder, string targerFolder, string userName, string passWord, string removePrefix = "")
{
try
{
if (string.IsNullOrEmpty(removePrefix))
{
removePrefix = sourceFolder;
}
if (!Directory.Exists(targerFolder))
{
Directory.CreateDirectory(targerFolder);
}
if (ConnectState(sourceFolder,userName,passWord))
{
DirectoryInfo directory = new DirectoryInfo(sourceFolder);
FileInfo[] files = directory.GetFiles();
foreach (FileInfo item in files)
{
if (item.Name == "Thumbs.db")
{
continue;
}
string tempPath = item.FullName.Replace(removePrefix, string.Empty);
tempPath = targerFolder + tempPath;
FileInfo fileInfo = new FileInfo(tempPath);
if (!fileInfo.Directory.Exists)
{
fileInfo.Directory.Create();
}
File.Delete(tempPath);
item.CopyTo(tempPath, true);
}
DirectoryInfo[] directors = directory.GetDirectories();
foreach (var item in directors)
{
CopyFiles(item.FullName, targerFolder,userName,passWord, removePrefix);
}
}
else
{
LoggerUtil.Info("连接服务器失败");
}
}
catch (Exception ex)
{
LoggerUtil.Error("CopyUtil:CopyFiles", ex);
}
}
四、调用方式
string ServicePath = CopyUtil.GetRemotePath("192.168.1.219", "D:\\log");
string ClientPath="D:\\DebugBase\\log";
CopyUtil.CopyFiles(ServicePath, ClientPath, "userName","passWord", null);