EDIT:
HttpWebRequestのを使用して、ファイルのな長さを取得し、サーバの応答に応じてディスクスペースを事前に割り当てます。要求が失敗した場合、ファイルの長さは0であり、ディスク領域は割り当てられません。
using System.IO;
using System.Net;
string URI = @"http://someserver/someresource.ext";
string FileName = @"c:\somefilename.ext";
//Get the File lenght and allocate disk space
Int64 FileSize = HTTP_GetFileSize(URI, FileName);
リソースの長さのためにサーバーを依頼し、それに応じてWebクライアント()を使用
public Int64 HTTP_GetFileSize(string URI, string FileName)
{
Int64 ResponseStreamLenght = 0;
HttpStatusCode _StatusCode;
HttpWebRequest httpRequest = WebRequest.CreateHttp(URI);
//Set User-Agent and Accept all formats
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0";
httpRequest.Accept = "*/*";
try
{
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
_StatusCode = httpResponse.StatusCode;
if (_StatusCode == HttpStatusCode.OK)
{
using (System.IO.Stream _stream = httpResponse.GetResponseStream())
{
//Get the lenght of the requested resource
ResponseStreamLenght = _stream.CanSeek == true
? _stream.Length
: httpResponse.ContentLength;
if (ResponseStreamLenght > 0)
{
using (FileStream fileApndStrm = new FileStream(FileName, FileMode.Create, FileAccess.Write))
{
//Create an empty file of ResponseStreamLenght size
fileApndStrm.SetLength(ResponseStreamLenght);
}
}
}
}
}
}
catch (WebException)
{
return 0;
}
catch (Exception)
{
return 0;
}
return ResponseStreamLenght;
}
をディスク領域を割り当て、リソースのために再度サーバーに尋ねます。
以前に使用されたファイル名を指定して、割り当てられたディスク領域を埋める。
//Download the file using the pre-allocated disk space
WebClient_DownLoad(URI, FileName);
public static void WebClient_DownLoad(string URI, string FileName)
{
using (WebClient _webclient = new WebClient())
{
// Add handlers to the events that give feedback on the download status
//and report the completion of the download
_webclient.DownloadFileCompleted += new AsyncCompletedEventHandler(WebClient_DownloadComplete);
_webclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WebClient_DownloadProgress);
//Asynchronous download of the resource
_webclient.DownloadFileAsync(new Uri(URI), FileName);
};
}
private static void WebClient_DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
// Update the UI with the transfer progress.
Console.Write("Received: {0} Total: {1} Percentage: {2}", e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
private static void WebClient_DownloadComplete(object sender, AsyncCompletedEventArgs e)
{
if (!e.Cancelled)
{
// Update the UI: transfer completed.
}
}
回答を更新しました。前の1つはおそらく少し謎だった。 – Jimi