我收到了异常
进程无法访问文件'C:\ Destination \ New Text Document.txt'因为它正被另一个进程使用。
我需要将所有源文件复制到目标文件夹。当Source和Destination中存在相同的命名文件时,我需要比较Hash值以了解两个文件是否具有相同的内容。如果找到相同的内容,我需要跳过复制过程,但如果内容不同,我需要复制文件。
我的班级结构如下:
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace TestBackups
{
public class FilesBackup
{
private string LookupDirectory;
private string BackupDirectory;
public FilesBackup()
{
LookupDirectory = "C:\\Source";
BackupDirectory = "C:\\Destination";
}
public void PerformBackup()
{
DirSearch(LookupDirectory);
}
public void DirSearch(string dir)
{
foreach (string file in Directory.GetFiles(dir))
{
// Console.WriteLine(string.Format("Filename : {0} and Lenghth : {1}", file, file.Length));
string destFilePath = file.Replace(LookupDirectory, BackupDirectory);
if (!File.Exists(file.Replace(LookupDirectory, BackupDirectory)))
{
Console.WriteLine("DO Not Exists - copy file");
File.Copy(file, destFilePath);
}
else
{
Console.WriteLine("Exists - check for the same content");
FileInfo sourceFile = new FileInfo(file);
FileInfo destinationFile = new FileInfo(destFilePath);
if (FilesAreEqual_Hash(sourceFile, destinationFile))
{
//Skip -Don't copy file
}
else
{
// Override the existing file
File.Copy(file, destFilePath, true);
}
}
}
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d);
}
}
public bool FilesAreEqual_Hash(FileInfo first, FileInfo second)
{
byte[] firstHash = MD5.Create().ComputeHash(first.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(second.OpenRead());
for (int i = 0; i < firstHash.Length; i++)
{
if (firstHash[i] != secondHash[i])
return false;
}
return true;
}
}
}
代码是工作文件,但当目标中存在相同的命名文件但内容不同时,生成异常。
我的控制台代码
using System;
namespace TestBackups
{
class Program
{
static void Main(string[] args)
{
try
{
FilesBackup backup= new FilesBackup();
backup.PerformBackup();
Console.ReadLine();
}
catch (Exception ex)
{
}
}
}
}
答案 0 :(得分:2)
Filestream是一次性用品。
byte[] firstHash = MD5.Create().ComputeHash(first.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(second.OpenRead());
尝试这样的事情:
byte[] firstHash, secondHash;
using (FileStream fs = File.OpenRead(first))
{
firstHash = MD5.Create().ComputeHash(fs);
}
using (FileStream fs = File.OpenRead(second))
{
secondHash = MD5.Create().ComputeHash(fs);
}