Scenario: The client (SharePoint Webpart) should provide a download to the user. Because of security reasons I can't access the file directly from the SharePoint Webpart. So I created an wcf webservice which sends the file as stream. But this dosen't work with bigger files.
WCF Webservice send Methode:
public Stream GetFileStream(string filePath)
{
WebClient client = new WebClient();
return client.OpenRead(filePath);
}
The client (SharePoint Webpart) get the stream and convert it in byte[] so I can create a download in the browser.
private void SendFileToBrowser(string filePath)
{
Page.Response.Clear();
Page.Response.ClearContent();
Page.Response.ClearHeaders();
Page.Response.ContentType = "application/pdf";
Page.Response.AddHeader("Content-Disposition", string.Format("attachment; fileName=\"{0}\"", Path.GetFileName(filePath)));
Page.Response.AddHeader("Accept-Ranges", "bytes");
byte[] buffer;
CustomBinding binding = new CustomBinding();
BinaryMessageEncodingBindingElement binaryMsg = new BinaryMessageEncodingBindingElement();
binaryMsg.ReaderQuotas.MaxDepth = 2147483647;
binaryMsg.ReaderQuotas.MaxStringContentLength = 2147483647;
binaryMsg.ReaderQuotas.MaxArrayLength = 2147483647;
binaryMsg.ReaderQuotas.MaxBytesPerRead = 2147483647;
binaryMsg.ReaderQuotas.MaxNameTableCharCount = 2147483647;
binding.Elements.Add(binaryMsg);
HttpTransportBindingElement transportBinding = new HttpTransportBindingElement();
transportBinding.TransferMode = TransferMode.Streamed;
transportBinding.MaxReceivedMessageSize = 2147483647;
binding.Elements.Add(transportBinding);
EndpointAddress endPoint = new EndpointAddress ("http://xxx/fileservice.svc");
FileServiceClient fileServiceProxy = new FileServiceClient(binding, endPoint);
// Stream
Stream stream = fileServiceProxy.GetFileStream(filePath);
fileServiceProxy.Close();
// convert stream to byte[]
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
buffer = memoryStream.ToArray();
}
if (buffer != null)
{
Page.Response.BinaryWrite(buffer);
}
Page.Response.Flush();
Page.Response.Close();
Page.Response.End();
}
The code works if the files are smaller > 300kb. But if the files are bigger (eg 50mb) it dosen't work always. But it works sometimes!??? I don't not what's wrong?