简体   繁体   English

使用WebClient(和silverlight)在.net中上传文件

[英]Uploading files in .net with WebClient (and silverlight)

I have the code below which I am using to upload files to my ashx page. 我有下面的代码用来将文件上传到ashx页面。 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); 现在,我假设它是在输出时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; 但是它继续到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). 我想这是因为它是在后台在单独的线程中进行编写的(或者我实际上是在查看错误的代码部分,并将其写在其他地方)-但是为了使totalBytesDone代码正常工作,我希望它锁定直到完成发送为止(我以后可以将其放在单独的线程中)。

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. 我已经下载了许多示例,它们要么不能与我的ashx文件处理程序一起正常工作(我无法更改它),要么它们使用仅报告50%进度的WebClient方法。

看看这个答案

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

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