views:

274

answers:

2

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.

+1  A: 

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.

marc_s
You sir, are correct. Works fine now. I doff my hat to you...
Alvin S
A: 

Check out this question. Lots of good advice, links, etc.

Terry Donaghe