将文件从一个位置复制到另一个位置
问题描述:
我试图创建一个目录和子目录,并将文件从一个位置复制到另一个位置。下面的代码有效,但如果有子目录,它不会创建父目录(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");
答
在做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/
答
这里是如何的所有目录中的文件复制到另一个目录
这是从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!");
}
答
这是不可能复制或在Windows 7
移动与C#文件,这反而创造了零个字节的文件。
Idk如果已经有一个简单的peasy库函数,但是您可以递归地检查子文件夹并复制每个文件夹。 – Amicable 2013-02-28 16:12:22
请检查http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c-sharp – 2013-02-28 16:13:33