Why is the WCF Stream response damaged when writing to disk?

I want to write a WCF web service that can send wiring files to a client. Therefore, I have one setting that sends a stream response. Here is my client code:

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 works fine, without errors and exceptions. The problem is that the .jpg file that receives the transmitted is reported as “damaged or too large” when I open it.

What am I doing wrong?

On the server side, this is the method that sends the file.

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

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

+4
source share
1 answer

I think the problem is this:

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

Imagine that you are reading the last bit of your file - maybe it's not 256 bytes, but just 10.

You read the last 10 bytes, bytesRead will be 10, but in the sink.Write operation you still use the fixed value of length (256). Therefore, when you read the last block of data, you write a block that may be too large.

You need to change the line for sink to:

  sink.Write(buffer, 0, bytesRead); 

and then it should work.

+4
source

Source: https://habr.com/ru/post/1299776/


All Articles