简体   繁体   中英

Uploading files in .net with WebClient (and silverlight)

I have the code below which I am using to upload files to my ashx page. It works great, although I cant seem to find a proper way of getting how much it has transferred.

The calling code:

WebClient wc = new WebClient();
wc.OpenWriteCompleted += (s2, e2) =>
{
   PushData(e2.Result, offset);
   e2.Result.Close();
};
wc.OpenWriteAsync(ub.Uri);

The push data code:

private void PushData(Stream output, long offset)
{
    byte[] buffer = new byte[4096];
    int bytesRead;
    bytesRead = theFileStream.Read(buffer, 0, buffer.Length);
    if (bytesRead != 0)
    {
        output.Write(buffer, 0, bytesRead);

        totalBytesDone += bytesRead;
        FireUpdateEvent(bytesRead);
    }
}

The above code is slightly different to my actual code, for brevity sake. Now, I had presumed that when it gets to output.Write(buffer,0,bytesRead); that that was the point where it sent the actual data and it would lock up and only goto the next line once its finished writing that section. But it goes on to totalBytesDone += bytesRead; before its written anything to the server. I presume the reason is that its doing the writing in a separate thread in the background (or I'm actually looking at the wrong section of code and it writes somewhere else) - but for my totalBytesDone code to work I want it to lock up until its finished sending (I can put this all in a seperate thread later).

I've downloaded tons of examples for doing this and they either dont work properly with my ashx file handler (I cant change it) or they use a WebClient method that just reports on 50% progress.

看看这个答案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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