在工作当中,难免会遇到需要自动将生成的文件上传至指定的云盘或共享盘当中,那这就无可避免的需要去书写一份上传的代码,以下是我自己的示列可供参考
主函数
static void Main(string[] args)
{
DataSaveToServer();
}
将文件复制进共享盘
static public bool DataSaveToServer()
{
try
{
// 本地文件夹 拼接
//string dataDir = Path.Combine(@"D:\MasterCheckLog\", @"2023-11-27");
string dataDir = Path.Combine(@"D:\MasterCheckLog\2023-11-27\", @"211224164243584_160228.jpg");
// 服务器文件夹 这个在需要换成192.168.250.10的共享盘路径
string serverDir = @"\\192.168.250.10\Temp1day每天凌晨两点清理数据\123";
// 可以不需要账号和密码,看是否需要
var state = ConnectState(serverDir, "Administrator", "123");
if (state == false)
{
//无法连接服务器
return false;
}
// 共享路径
string destDir = Path.Combine(serverDir, @"Dest\");
if (File.Exists(dataDir))
{
CopyFileAndDir(dataDir, destDir);
return true;
}
return false;
}
catch (Exception ex)
{
//操作失败
Console.WriteLine(ex.Message);
return false;
}
}
连接远程共享文件夹
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)
{
Console.WriteLine(ex.Message);
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
复制文件夹下的所有文件、目录到指定的文件夹
private static void CopyFileAndDir(string dir, string desDir)
{
//文件夹不存在,则新建 这里可能存在访问权限的问题,一定要给共享权限
if (!Directory.Exists(desDir))
{
Directory.CreateDirectory(desDir);
}
// 这里是文件夹内的所有文件进行转存,通过遍历获取所有文件名来进行存入
//IEnumerable<string> files = Directory.EnumerateFiles(dir);
//if (files != null && files.Count() > 0)
//{
// foreach (var item in files)
// {
// string desPath = Path.Combine(desDir, Path.GetFileName(item));
// //如果是文件
// var fileExist = File.Exists(item);
// if (fileExist)
// {
// //复制文件到指定目录下
// File.Copy(item, desPath, true);
// continue;
// }
// //如果是文件夹
// CopyFileAndDir(item, desPath);
// }
//}
// 这里是直接转存文件到共享盘当中
string item = dir.Substring(dir.LastIndexOf(@"\")).Replace("\\"," ").Trim();
string desPath = Path.Combine(desDir, Path.GetFileName(item));
File.Copy(dir, desPath, true);
}
该方法是直接通过cmd来进行上传至共享盘的,存在耗时,若传输的数据太大,并且是同步的情况下会造成程序卡死,请留意!