将文件从一个位置复制到另一个位置

我正在尝试创建一个目录和子目录,并将文件从一个位置复制到另一个位置。 以下代码有效但如果有子目录则不会创建父目录(10_new)。 我试图将所有内容(包括子目录)从"c:\\sourceLoc\\10""c:\\destLoc\\10_new"文件夹。 如果"10_new"不存在,那么我应该创建这个文件夹。 请协助。

 string sourceLoc = "c:\\sourceLoc\\10"; string destLoc = "c:\\destLoc\\10_new"; foreach (string dirPath in Directory.GetDirectories(sourceLoc, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourceLoc, destLoc)); if (Directory.Exists(sourceLoc)) { //Copy all the files foreach (string newPath in Directory.GetFiles(sourceLoc, "*.*", SearchOption.AllDirectories)) File.Copy(newPath, newPath.Replace(sourceLoc, destLoc)); } } 

从查看代码开始,您永远不会检查父文件夹是否存在。 您首先跳转到获取所有子文件夹。

 if (!Directory.Exists(@"C:\my\dir")) Directory.CreateDirectory(@"C:\my\dir"); 

以下是如何将目录中的所有文件复制到另一个目录

这取自http://msdn.microsoft.com/en-us/library/cc148994.aspx

  string sourcePath = "c:\\sourceLoc\\10"; string targetPath = "c:\\destLoc\\10_new"; string fileName = string.Empty; string destFile = string.Empty; // To copy all the files in one directory to another directory. // Get the files in the source folder. (To recursively iterate through // all subfolders under the current directory, see // "How to: Iterate Through a Directory Tree.") // Note: Check for target path was performed previously // in this code example. if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = System.IO.Path.GetFileName(s); destFile = System.IO.Path.Combine(targetPath, fileName); System.IO.File.Copy(s, destFile, true); } } else { Console.WriteLine("Source path does not exist!"); } 

在执行File.Copy之前,请检查以确保该文件夹存在。 如果它没有创建它。 此函数将检查路径是否存在,如果不存在,则会创建它。 如果它无法创建它,出于任何原因,它将返回false。 否则,是的。

  Private Function checkDir(ByVal path As String) As Boolean Dim dir As New DirectoryInfo(path) Dim exist As Boolean = True If Not dir.Exists Then Try dir.Create() Catch ex As Exception exist = False End Try End If Return exist End Function 

请记住,所有.Net语言都编译为CLR(公共语言运行库),因此无论是在VB.Net还是C#中都无关紧要。 在两者之间进行转换的好方法是: http : //converter.telerik.com/

在Windows 7中无法使用C#复制或移动文件。

它将创建一个零字节的文件。