标签:c#实现服务器间文件传输
最近需要做站点迁移,但是服务器间拷贝站点,经常出问题,只要一按Ctrl+V,就报错。后来大家建议写个程序来实现批量拷贝,所以就展示下代码,讲下坑
界面
代码:
private void runbutton_Click(object sender, EventArgs e) { string srcIP = srctb.Text; string desIP = destb.Text; string siteListStr = sitelisttb.Text; string [] siteList = siteListStr.Split(‘;‘); logtb.Text = ""; foreach(string site in siteList) { if (!site.Equals("")) { StringBuilder log = FileUtils.CopySite(srcIP, desIP, site); logtb.Text = logtb.Text + log; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CopySite { public class FileUtils { public static StringBuilder CopySite(string srcIp, string desIp, string site) { string srcpath = System.IO.Path.Combine("\\\\", srcIp, "WebSites", site); string despath = System.IO.Path.Combine("\\\\", desIp, "WebSites", site); bool overwrite=true; StringBuilder log=new StringBuilder(); CopyDir(srcpath, despath, overwrite, ref log); return log; } public static void CopyDir(string srcpath, string despath, bool overwrite, ref StringBuilder log) { if (!Directory.Exists(srcpath)) { log.AppendLine(srcpath+"不存在"); return; } // 判断文件夹存不存在 if (!Directory.Exists(despath)) { Directory.CreateDirectory(despath); log.AppendLine( despath+"创建成功"); } // 复制文件 string[] files = System.IO.Directory.GetFiles(srcpath); foreach (string s in files) { //仅返回路径字符串的文件名及后缀 string fileName = System.IO.Path.GetFileName(s); string destFile = System.IO.Path.Combine(despath, fileName); CopyFile(s, destFile, overwrite); log.AppendLine(destFile + "拷贝成功"); } //复制Dir string[] dirs = Directory.GetDirectories(srcpath); foreach (string dir in dirs) { string dirName = System.IO.Path.GetFileName(dir); string newdespath = System.IO.Path.Combine(despath, dirName); CopyDir(dir, newdespath, overwrite, ref log); } } public static void CopyFile(string srcpath,string despath,bool overwrite) { File.Copy(srcpath, despath, overwrite); } } }
假设:需要实现从A拷贝文件到B
坑1:在本地执行该代码,提示目标源访问不了
原因:我本机在上海的域中,源机子跟目标机子都在南通的域中,不同域之间访问存在问题(虽然手动是可以拷贝的)
坑2:把程序放到B机器上运行,还是报目标源访问不了
原因:A上有DMZ访问限制,所以B机器上代码访问不了A
正确解决方法:程序运行在A机器上,并且把B机器上要访问的目录设成共享目录
本文出自 “爱工作爱生活” 博客,转载请与作者联系!
标签:c#实现服务器间文件传输
原文地址:http://4453154.blog.51cto.com/4443154/1716005