public static void CheckFileOrCreateFile(IDownloader downloader, object fileLocker)
{
// Lock other threads or processes to prevent from creating the file.
lock (fileLocker)
{
FileInfo fileToDownload = new FileInfo(downloader.DownloadPath);
if (fileToDownload.Exists)
{
// The destination file should have the same size as the file to be downloaded.
if (fileToDownload.Length != downloader.TotalSize)
{
throw new ApplicationException(
"The download path already has a file which does not match"
+ " the file to download. ");
}
}
// Create a file.
else
{
if (downloader.TotalSize == 0)
{
throw new ApplicationException("The file to download does not exist!");
}
using (FileStream fileStream = File.Create(downloader.DownloadPath))
{
long createdSize = 0;
byte[] buffer = new byte[4096];
while (createdSize < downloader.TotalSize)
{
int bufferSize = (downloader.TotalSize - createdSize) < 4096
? (int)(downloader.TotalSize - createdSize) : 4096;
fileStream.Write(buffer, 0, bufferSize);
createdSize += bufferSize;
}
}
}
}
}