PDJJ14 WIKI : BinaryReader/Writer 를 이용한 File Copy & MD5 를 이용한 checksum
Created by 한재중, last modified on 5월 04, 2018
6. 코드
private bool FileCopy(string source, string destination)
{
int array_length = (int)Math.Pow(2, 19);
byte[] dataArray = new byte[array_length];
using (FileStream fsread = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None, array_length))
{
using (BinaryReader bwread = new BinaryReader(fsread))
{
using (FileStream fswrite = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None, array_length))
{
using (BinaryWriter bwwrite = new BinaryWriter(fswrite))
{
for (;;)
{
int read = bwread.Read(dataArray, 0, array_length);
if (0 == read) break;
bwwrite.Write(dataArray, 0, read);
}
}
}
}
}
//return string.Equals(CalcuateMD5(source), CalcuateMD5(destination)); //checksum 을 할 때만 사용. 안 할거면 그냥 void 로 선언
return true;
}
private string CalcuateMD5(string fileName)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(fileName))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
7. 테스트
private void button4_Click(object sender, EventArgs e)
{
DateTime start, end;
double fileCopyDuration = 0, binaryWriteCopyDuration = 0;
string sourceFilePath = @"..\Test\Source\Data.zip";
string targetFolderPath = @"..\Test\Target\Data.zip";
int maxCount = 10;
bool binaryCopyResult = false;
for (int count = 0; count < maxCount; ++count)
{
if (File.Exists(targetFolderPath)) File.Delete(targetFolderPath);
start = DateTime.Now;
File.Copy(sourceFilePath, targetFolderPath);
end = DateTime.Now;
fileCopyDuration += (end - start).TotalSeconds;
if (File.Exists(targetFolderPath)) File.Delete(targetFolderPath);
start = DateTime.Now;
binaryCopyResult = FileCopy(sourceFilePath, targetFolderPath);
end = DateTime.Now;
binaryWriteCopyDuration += (end - start).TotalSeconds;
}
MessageBox.Show(string.Format("File Copy average duration: {0}sec, BinaryWriteCopy avg duration: {1}sec, BinaryWriteResult: {2}",
(fileCopyDuration / (double)maxCount), (binaryWriteCopyDuration / (double)maxCount), binaryCopyResult));
}
7.1. 결과
- 1.57GB 파일 한개를 한번 전송
- File Copy: 2.3 sec
- Binary Copy: 1.5 sec
- Binary Copy including checksum: 11.7 sec
- 1.57GB 파일 한개를 14번 전송 평균
- File Copy: 2.3 sec
- Binary Copy: 2.0 sec
- Binary Copy including checksum: 12.2 sec