【问题标题】:Error on making resumeable download in c#在 C# 中进行可恢复下载时出错
【发布时间】:2012-01-08 16:29:22
【问题描述】:

我正在尝试使用 c# 测试可恢复下载。我发现通过查看一些博客添加范围会有所帮助。但是在下面的代码中 add range 没有任何意义。 伙计们建议我如何解决这个问题。 什么方法可以有效地进行可恢复下载?

HttpWebRequest myrequest = null;
    HttpWebResponse myresponse = null;
    private int interval=2048;
    public bool set_url(string todonwloads,string tosaves)
    {
        this.todownload = todonwloads;
        this.tosave = tosaves;
        return true;
    }
    public bool start_download()
    {
        myrequest = (HttpWebRequest)WebRequest.Create(this.todownload);
       // it the following code. 
       //If i dont write addrange. It will download same portion of the file.
        myrequest.AddRange(4000,8000);

        try
        {
            myresponse = (HttpWebResponse)myrequest.GetResponse();
            if (myresponse.StatusCode == HttpStatusCode.OK)
            {
                Stream ReceiveSteam = myresponse.GetResponseStream();
                FileStream fs = new FileStream(
                                        this.tosave, 
                                        FileMode.Create, 
                                        FileAccess.Write, 
                                        FileShare.None);
                int reads;
                byte[] buffer = new byte[this.interval];
                while ((reads = ReceiveSteam.Read(
                                         buffer, 
                                         0, 
                                         this.interval)) > 0)
                {
                    fs.Write(buffer, 0, reads);
                }
                return true;
            }


        }
        catch (WebException ex)
        {

            throw ex;
        }
        finally
        {
            if (myresponse != null)
            {
                myresponse.Close();
            }
        }
        return false;

    }

【问题讨论】:

    标签: c# httprequest httpresponse


    【解决方案1】:

    您当前每次下载文件的一部分时都会创建并覆盖该文件:

    //            Overwrites the file each time -\/
    ... = new FileStream(this.tosave, FileMode.Create, ...
    

    您需要打开或创建使用FileMode.OpenOrCreate 的文件,然后查找您写入文件的最后一部分:

    // seek to the last end offset, you'll need to save this somehow
    fs.Seek(lastOffset, SeekOrigin.Begin);
    
    int reads;
    byte[] buffer = new byte[this.interval];
    while ((reads = ReceiveSteam.Read(buffer, 0, this.interval)) > 0)
    {
        fs.Write(buffer, 0, reads);
        lastOffset += reads;
    }
    

    【讨论】:

    • 呀。我明白了。但我想问的是下载。即使我在代码中插入添加范围。应用程序下载它的所有部分并写入文件..
    • The server may not support the Range header。尝试打印myresponse.Headers.ToString(),看看是否有Accept-Ranges: bytes
    猜你喜欢
    • 2019-05-30
    • 2013-07-21
    • 1970-01-01
    • 2012-10-19
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多