分段C#文件下载器

时间:2009-12-02 07:52:13

标签: c# download httpwebresponse

一直在尝试用C#编写程序,像大多数下载管理器一样使用多个段下载文件,而且我遇到了下载的文件已损坏的问题。例如,我下载了一段视频,它播放了2秒,然后WMP说它无法播放。

我对下载的文件进行了咒骂,看来整个文件中都有零散的部分,任何人都有什么想法? VS报告没有错误。

在单独的线程中为每个段调用

getPart()

public long start;
public long end;
public int thread;
public Form1 handle;
public myFile handler;
public void getPart()
{
    log("getting part " + start.ToString() + "," + end.ToString());
    HttpWebRequest part = (HttpWebRequest)WebRequest.Create(handler.url);
    part.AddRange((int)start,(int) end);
    HttpWebResponse pr = (HttpWebResponse)part.GetResponse();
    Stream rstream = pr.GetResponseStream();
    log("Beginning part " + start.ToString());
    int totalbytes = 0;
    byte[] buffer = new byte[256];
    int x = rstream.Read(buffer, 0, 256);
    while (x > 0)
    {
        handler.writeFile(buffer, (int)(totalbytes + start), x);
        totalbytes += x;
        x = rstream.Read(buffer, 0, 256);
    }
    log(start.ToString() + "-byte start part done...");
    rstream.Close();
    pr.Close();
    handler.partDone(thread);
    return;
}

public void writeFile(byte[] buffer, int start, int size)
{
    mFileStream.Seek(start, SeekOrigin.Begin);
    mFileStream.Write(buffer, 0, size);
    return;
}

1 个答案:

答案 0 :(得分:11)

嗯,我已经弄明白了,只是觉得我会给任何有类似问题的人留下答案。文件写入流周围需要锁定。

public void writeFile(byte[] buffer, int start, int size)
    {
        mFileStream.Seek(start, SeekOrigin.Begin);
        mFileStream.Write(buffer, 0, size);
        return;
    }

变为

public void writeFile(byte[] buffer, int start, int size)
    {
        lock (mFileStream)
        {
        mFileStream.Seek(start, SeekOrigin.Begin);
        mFileStream.Write(buffer, 0, size);
        return;
        }
    }