C#, How to download file into string with progress callback?

Posted by Kaminari on Stack Overflow See other posts from Stack Overflow or by Kaminari
Published on 2010-04-26T11:45:11Z Indexed on 2010/04/26 12:03 UTC
Read the original article Hit count: 164

Filed under:
|
|

I would like to use the WebClient (or there is another better option?) but there is a problem. I understand that opening up the stream takes some time and this can not be avoided. However, reading it takes a strangely much more amount of time compared to read it entirely immediately.

Of course it's not working good because i'm not so familiar with streams. Is there a best way to do this? I mean two ways, to string and to file. Progress is my own delegate and it's working good.


FIRST UPDATE:

Ok, now i got something like this and it seems to work but still slow:

System.Net.WebClient client = new System.Net.WebClient();
        System.IO.Stream streamRemote = client.OpenRead(new Uri(URL));
        if (savePath == null)
        {
            StreamReader reader = new StreamReader(streamRemote);
            int iByteSize = 0;
            byte[] byteBuffer = new byte[iSize];
            char[] charBuffer = new char[iSize];
            StringBuilder sb = new StringBuilder();
            while ((iByteSize = reader.Read(charBuffer, 0, iSize)) > 0)
            {
                sb.Append(charBuffer, 0, iByteSize);
                iRunningByteTotal += iByteSize;
                float dIndex = (float)(iRunningByteTotal);
                float dTotal = (float)byteBuffer.Length;
                float dProgressPercentage = (dIndex / dTotal);
                float iProgressPercentage = (dProgressPercentage * 100);

                if (Progress != null) Progress(iProgressPercentage);
            }
            result = sb.ToString();

        }

Im wondering about DownloadStringAsync method?

© Stack Overflow or respective owner

Related posts about c#

Related posts about webclient