c# 通过文件夹共享复制文件到服务器

时间:2021-05-11 04:12:34

public static string[] GetFileNames(string directoryPath, string searchName)
{
return Directory.GetFiles(directoryPath, searchName, SearchOption.AllDirectories);
}


public class NetFileConntion
{
public static bool ConnectState(string path)
{
return ConnectState(path, "", "");
} 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 * /del /y
net use " + path + " /User:" + userName + " " + passWord + " /PERSISTENT:YES";
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine(" exit ");
while (!proc.HasExited)
{
proc.WaitForExit();
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
flag = true;
}
else
{
throw new Exception(errormsg);
}
}
finally
{
proc.Close();
proc.Dispose();
}
return flag;
}
}
 /// <summary>
/// 数据处理
/// </summary>
public override void Execute(JobExcutePara para)
{
if (ConfigHelper.Settings("RemoteCopyFileSwitch") != "")
{
return;
} //读取所有文件
var files = DirFileHelper.GetFileNames(ExcelRootPath, "*.*").Where(t => t.Contains("\\U_")).ToList();
//远程地址
var remotepaths = ConfigHelper.Settings("RemoteRootPaths")
.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
var remoteusers = ConfigHelper.Settings("RemoteUserPass")
.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
var sr=new StringBuilder();
foreach (var remotepath in remotepaths)
{
sr.Append(remotepath + ",");
try
{
bool status = NetFileConntion.ConnectState(remotepath, remoteusers[], remoteusers[]);
sr.Append(status + "," + files.Count + "," + remoteusers[] + "," + remoteusers[]);
if (status)
{
var startTime = new DateTime(DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
, , );
//读取目标目录文件
var theFiles = DirFileHelper.GetFileNames(remotepath, "*.*");
sr.Append(theFiles.Length + ","); foreach (var file1 in files)
{
var fileinfo_1=new FileInfo(file1);
if (fileinfo_1.LastWriteTime < startTime)
{
continue;
}
var filepath = file1.Replace(ExcelRootPath, string.Empty);
var flag = false;
foreach (var file2 in theFiles)
{
//检查文件是否存在
if (file2.Contains(filepath))
{
flag = true;
break;
}
}
if (!flag)
{
//没有则进行写入复制
var targetPath = remotepath + filepath;
if (!Directory.Exists(Path.GetDirectoryName(targetPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
}
File.Copy(file1, targetPath);
}
}
}
}
catch (Exception ex)
{
LogHelper._Error("JobExcute__CopyFile ERROR", ex);
}
}
//LogHelper._Info(sr.ToString());
}