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

Posted by Alvin S on Stack Overflow See other posts from Stack Overflow or by Alvin S
Published on 2010-01-29T21:17:05Z Indexed on 2010/04/28 3:23 UTC
Read the original article Hit count: 651

Filed under:
|
|
|
|

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 exceptions. 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.

© Stack Overflow or respective owner

Related posts about wcf

Related posts about stream