我需要将文件夹C:\ FromFolder复制到C:\ ToFolder
下面的代码将剪切我的FromFolder,然后将创建我的ToFolder.所以我的FromFolder将会消失,所有项目都将在新创建的名为ToFolder的文件夹中
System.IO.Directory.Move(@"C:\FromFolder ", @"C:\ToFolder");
但我只是想将FromFolder中的文件复制到ToFolder.由于某种原因,没有System.IO.Directory.Copy ???
如何使用批处理文件完成此操作 - 非常简单
xcopy C:\ FromFolder C:\ ToFolder
问候艾蒂安
有一个文件副本.重新创建文件夹并将原始目录中的所有文件复制到新的 示例中
static void Main(string[] args) { DirectoryInfo sourceDir = new DirectoryInfo("c:\\a"); DirectoryInfo destinationDir = new DirectoryInfo("c:\\b"); CopyDirectory(sourceDir, destinationDir); } static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination) { if (!destination.Exists) { destination.Create(); } // Copy all files. FileInfo[] files = source.GetFiles(); foreach (FileInfo file in files) { file.CopyTo(Path.Combine(destination.FullName, file.Name)); } // Process subdirectories. DirectoryInfo[] dirs = source.GetDirectories(); foreach (DirectoryInfo dir in dirs) { // Get destination directory. string destinationDir = Path.Combine(destination.FullName, dir.Name); // Call CopyDirectory() recursively. CopyDirectory(dir, new DirectoryInfo(destinationDir)); } }
此链接提供了一个很好的示例.
http://msdn.microsoft.com/en-us/library/cc148994.aspx
这是一个片段
// 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); } }
复制目录(正确)实际上是一项相当复杂的任务,尤其是考虑到交叉点和硬链接等高级文件系统技术.您最好的选择是使用支持它的API.如果你不怕一点P/Invoke,shell32中的SHFileOperation是你最好的选择.另一种方法是在Microsoft.VisualBasic程序集中使用Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory方法(即使您没有使用VB).