如何在窗体应用程序中下载文件并通过ProgressBar显示下载进度?
RestClient client = new RestClient("http://127.0.0.1/");
RestRequest request = new RestRequest("/test/{FileName}");
request.AddParameter("FileName", "testFile.abc", ParameterType.UrlSegment);
string path = @"C:/Users/[user]/Desktop/testFile.abc";
var fileForDownload = client.DownloadData(request);
fileForDownload.SaveAs(path);
if (File.Exists(@"C:/Users/[user]/Desktop/testFile.abc"))
{
MessageBox.Show("done");
}
我写这样的想法,但我现在不知道什么?
答案 0 :(得分:6)
我认为更好的替代方法是覆盖FileStream以获取写入文件的字节数:
string tempFile = Path.Combine(Configuration.DownloadFolder, "TEST.DATA");
using (var writer = new HikFileStream(tempFile))
{
writer.Progress += (w, e) => {
#if DEBUG
Console.Write(string.Format("\rProgress: {0} / {1:P2}", writer.CurrentSize, ((double)writer.CurrentSize) / finalFileSize));
#endif
};
request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer);
var response = client.DownloadData(request);
}
HikFileStream是:
class HikFileStream : FileStream
{
public HikFileStream(string path)
: base(path, FileMode.Create, FileAccess.Write, FileShare.None)
{
}
public long CurrentSize { get; private set; }
public event EventHandler Progress;
public override void Write(byte[] array, int offset, int count)
{
base.Write(array, offset, count);
CurrentSize += count;
var h = Progress;
if (h != null)
h(this, EventArgs.Empty);//WARN: THIS SHOULD RETURNS ASAP!
}
}
答案 1 :(得分:1)
很抱歉,但是你不能,因为RestClient中没有事件处理程序对象来获取下载数据的状态。
这是另一种方法;
http.createServer()
更改" timer1"的名称用于命名最佳实践。祝你好运......