开发者

Why is WCF Stream response getting corrupted on write to disk?

I am wanting to write a WCF web service that can send files over the wire to the client. So I have one setup that sends a Stream response. Here is my code on the client:

private void button1_Click(object sender, EventArgs e)
{
    string filename = System.Environment.CurrentDirectory + "\\Picture.jpg";
    if (File.Exists(filename))
        File.Delete(filename);

    StreamServiceClient client = new StreamServiceClient();

    int length = 256;
    byte[] buffer = new byte[length];
    FileStream sink = new FileStream(filename, FileMode.CreateNew, FileAccess.Write);
    Stream source = client.GetData();
    int bytesRead;
    while ((bytesRead = source.Read(buffer,0,length))> 0)
    {
        sink.Write(buffer,0,length);
    }
    source.Close();
    sink.Close();
    MessageBox.Show("All done");
}

Everything processes fine with no errors or except开发者_开发问答ions. The problem is that the .jpg file that is getting transferred is reported as being "corrupted or too large" when I open it.

What am I doing wrong?

On the server side, here is the method that is sending the file.

public Stream GetData()
{
    string filename = Environment.CurrentDirectory+"\\Chrysanthemum.jpg";
    FileStream myfile = File.OpenRead(filename);
    return myfile;
}

I have the server configured with basicHttp binding with Transfermode.StreamedResponse.


I think the problem is this:

while ((bytesRead = source.Read(buffer,0,length))> 0)
{
    sink.Write(buffer,0,length);
}

Imagine you're reading the last bit of your file - maybe it's not 256 bytes anymore, but only 10.

You read those last 10 bytes, bytesRead will be 10, but on the sink.Write operation, you're still using the fixed value length (256). So when you read the last block of data, you're writing out a block that might be too large.

You need to change the line for the sink to:

   sink.Write(buffer, 0, bytesRead);

and then it should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜