概述
如何将所有文件从一个目录复制到另一个目录并用 C# 覆盖目标目录中所有现有的同名文件?
我有以下代码将文件从一个目录复制到另一个目录...
const string sourceDir = @"C:\AppProject\Smart\SmartStaff\site\document";
const string targetDir = @"C:\AppProject\Smart\ExternalSmartStaff\site\document";
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
...,但是当目标目录已经包含与源目录中的文件同名的文件时,它会失败并出现错误System.IO.IOException: The file 'C:\AppProject\Smart\ExternalSmartStaff\site\document\SomeDocument.txt' already exists.
。
细节
要清楚,给定以下目录和文件...
C:\>dir C:\AppProject\Smart\SmartStaff\site\document
...
Directory of C:\AppProject\Smart\SmartStaff\site\document
09/03/2014 06:38 PM <DIR> .
09/03/2014 06:38 PM <DIR> ..
05/25/2014 08:29 PM 44 SomeDocument.txt
05/25/2014 08:32 PM 21 SomeDocument2.txt
05/25/2014 08:36 PM 21 SomeDocument3.txt
05/25/2014 08:43 PM 44 SomeDocument4.txt
4 File(s) 130 bytes
2 Dir(s) 128,326,766,592 bytes free
C:\>dir C:\AppProject\Smart\ExternalSmartStaff\site\document
...
Directory of C:\AppProject\Smart\ExternalSmartStaff\site\document
09/03/2014 06:39 PM <DIR> .
09/03/2014 06:39 PM <DIR> ..
09/03/2014 06:39 PM 26 SomeDocument.txt
09/03/2014 06:39 PM 54 SomeDocument2.txt
2 File(s) 80 bytes
2 Dir(s) 128,326,766,592 bytes free
...,我想C:\AppProject\Smart\ExternalSmartStaff\site\document
在 C# 中的文件复制后看起来像这样:
C:\>dir C:\AppProject\Smart\ExternalSmartStaff\site\document
...
Directory of C:\AppProject\Smart\ExternalSmartStaff\site\document
09/03/2014 06:47 PM <DIR> .
09/03/2014 06:47 PM <DIR> ..
05/25/2014 08:29 PM 44 SomeDocument.txt
05/25/2014 08:32 PM 21 SomeDocument2.txt
05/25/2014 08:36 PM 21 SomeDocument3.txt
05/25/2014 08:43 PM 44 SomeDocument4.txt
4 File(s) 130 bytes
2 Dir(s) 128,327,835,648 bytes free
我怎样才能避免IOException
并做到这一点?