简体   繁体   English

分段C#文件下载器

[英]Segmented C# file downloader

Have been trying to write a program in C# that downloads a file using multiple segments at once like most download managers, and I've run into the issue that the files downloaded are corrupted. 一直在尝试用C#编写程序,像大多数下载管理器一样使用多个段下载文件,我遇到了下载的文件已损坏的问题。 Eg, I download a video and it plays for 2 seconds then WMP says it's unplayable. 例如,我下载一个视频,它播放2秒,然后WMP说它无法播放。

I hexedited the downloaded file and it appears there are sections of zerobytes scattered throughout the file, anyone have any ideas why? 我对下载的文件进行了咒骂,看起来整个文件中都有零散的部分,任何人有什么想法? VS reports no errors. VS报告没有错误。

getPart() is called for each segment in a separate thread. 在单独的线程中为每个段调用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;
}

Well I've figured it out, just thought I'd leave an answer for anyone having similar issues. 好吧,我已经弄清楚了,只是觉得我会给任何有类似问题的人留下答案。 A lock is required around the file writing stream. 文件写入流周围需要锁定。

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

becomes

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM