2012-03-15 29 views

Trả lời

6

Một phương pháp mẫu tôi sử dụng để tải về các tập tin từ dịch vụ REST của tôi:

[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); 
     } 
+0

Cảm ơn rất nhiều! Tôi sẽ làm việc với điều này. – fiberOptics

+11

Bất kỳ lý do nào khiến bạn không trực tiếp trả lại FileStream? Và nếu bạn thực sự muốn sao chép luồng, .Net4 có phương thức CopyTo trên luồng. –

+1

Có thể không liên quan nữa, nhưng việc trả lại trực tiếp FileStream có thể gây ra sự cố với tệp không được đính kèm. – steavy

Các vấn đề liên quan