标签:
写移动文件练习时候发现Directory.move只能在同一个盘符进行操作,于是度娘一下,还真有人也遇到这种情况,搜索一番发现一位仁兄写的一个跨盘符移动的demo很好分享一下,原文如下:
1 public void MoveDirectory(string strSourceDir, string strDestDir, bool bDelSource) 2 { 3 if (Directory.Exists(strSourceDir)) 4 { 5 if (Directory.GetDirectoryRoot(strSourceDir) == Directory.GetDirectoryRoot(strDestDir)) 6 { 7 Directory.Move(strSourceDir, strDestDir); 8 } 9 else 10 { 11 try 12 { 13 CopyDirectory(new DirectoryInfo(strSourceDir), new DirectoryInfo(strDestDir)); 14 if (bDelSource) Directory.Delete(strSourceDir, true); 15 } 16 catch (Exception subEx) 17 { 18 throw subEx; 19 } 20 } 21 } 22 } 23 private void CopyDirectory(DirectoryInfo diSourceDir, DirectoryInfo diDestDir) 24 { 25 if (!diDestDir.Exists) diDestDir.Create(); 26 FileInfo[] fiSrcFiles = diSourceDir.GetFiles(); 27 foreach (FileInfo fiSrcFile in fiSrcFiles) 28 { 29 fiSrcFile.CopyTo(Path.Combine(diDestDir.FullName, fiSrcFile.Name)); 30 } 31 DirectoryInfo[] diSrcDirectories = diSourceDir.GetDirectories(); 32 foreach (DirectoryInfo diSrcDirectory in diSrcDirectories) 33 { 34 CopyDirectory(diSrcDirectory, new DirectoryInfo(Path.Combine(diDestDir.FullName, diSrcDirectory.Name))); 35 } 36 } 37 private void button1_Click(object sender, EventArgs e) 38 { 39 //MoveFolder1(); 40 string sNowFile = System.Windows.Forms.Application.StartupPath + "\\seo"; 41 string sNFile = Environment.SystemDirectory.Replace("system32", ""); 42 MoveDirectory(sNowFile, sNFile, true); 43 }
简简单单代码让人豁然开朗,其实我们可以换个角度,他进行的是创建路径去遍历源地址文件复制到目的地址,然后删除原文件。这样就解决了,代码很容易懂赞一下!
标签:
原文地址:http://www.cnblogs.com/dylanblog/p/4179801.html