BiliRanking.Core.Download.DownloaderHelper.CheckFileOrCreateFile C# (CSharp) Method

CheckFileOrCreateFile() public static method

Check whether the destination file exists. If not, create a file with the same size as the file to be downloaded.
public static CheckFileOrCreateFile ( IDownloader downloader, object fileLocker ) : void
downloader IDownloader
fileLocker object
return void
        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;
                        }
                    }
                }
            }
        }

Usage Example

Exemplo n.º 1
0
 /// <summary>
 /// Check whether the destination file exists. If  not, create a file with the same
 /// size as the file to be downloaded.
 /// </summary>
 void CheckFileOrCreateFile()
 {
     DownloaderHelper.CheckFileOrCreateFile(this, locker);
 }