Download file using WCF Rest service?

15,327

A sample method i use to download the file from my REST service:

[WebGet(UriTemplate = "file/{id}")]
        public Stream GetPdfFile(string id)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt";
            FileStream f = new FileStream("C:\\Test.txt", FileMode.Open);
            int length = (int)f.Length;
            WebOperationContext.Current.OutgoingResponse.ContentLength = length;
            byte[] buffer = new byte[length];
            int sum = 0;
            int count;
            while((count = f.Read(buffer, sum , length - sum)) > 0 )
            {
                sum += count;
            }
            f.Close();
            return new MemoryStream(buffer); 
        }
Share:
15,327
fiberOptics
Author by

fiberOptics

learner

Updated on July 26, 2022

Comments

  • fiberOptics
    fiberOptics over 1 year

    If there is a way to Upload file using rest via stream would there be also for "Download"? If yes, can you please tell me how? Thanks in advance!

  • Darrel Miller
    Darrel Miller about 12 years
    Any reason why you don't return the FileStream directly? And if you really want to copy the stream, .Net4 has a CopyTo method on streams.
  • steavy
    steavy about 9 years
    Probably not relevant anymore, but returning FileStream directly might cause problems with unclosed file.
  • steavy
    steavy about 9 years
    And about CopyTo - don`t forget to reset position of the stream to 0 after copying file into MemoryStream. Otherwise you will have empty file on the calling side.