Domanda

Sto cercando di scaricare dati utilizzando un oggetto WebClient in blocchi del 5% ciascuno. Il motivo è che devo segnalare progressi per ogni pezzo scaricato.

Ecco il codice che ho scritto per fare questo compito:

    private void ManageDownloadingByExtractingContentDisposition(WebClient client, Uri uri)
    {
        //Initialize the downloading stream 
        Stream str = client.OpenRead(uri.PathAndQuery);

        WebHeaderCollection whc = client.ResponseHeaders;
        string contentDisposition = whc["Content-Disposition"];
        string contentLength = whc["Content-Length"];
        string fileName = contentDisposition.Substring(contentDisposition.IndexOf("=") +1);

        int totalLength = (Int32.Parse(contentLength));
        int fivePercent = ((totalLength)/10)/2;

        //buffer of 5% of stream
        byte[] fivePercentBuffer = new byte[fivePercent];

        using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
        {
            int count;
            //read chunks of 5% and write them to file
            while((count = str.Read(fivePercentBuffer, 0, fivePercent)) > 0);
            {
                fs.Write(fivePercentBuffer, 0, count);
            }
        }
        str.Close();
    }

Il problema: quando arriva a str.read (), fa una pausa tanto quanto leggere l'intero flusso, e quindi il conta è 0. Quindi il why () non funziona, anche se ho specificato per leggere solo quanto il variabile a cinque percentuali. Sembra proprio che legga l'intero flusso nel primo tentativo.

Come posso farlo in modo che legga i pezzi correttamente?

Grazie,

Andrei

Nessuna soluzione corretta

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top