.::  Downloading a remote file to a MemoryStream using C# (CSharp)  ::.

A MemoryStream is my preferred method of passing around file data throughout my .Net applications. The following code details a simple way to download a file and place it in the memory stream.

Situation:
Download a PDF from a remote location and store data in a MemoryStream. The MemoryStream needs will be accessed multiple times in a single instance from other OO objects.

Underlying Technology:
Microsoft .Net FCL (Framework Class Library)

The Code:
The following code is deigned for use in a class file that is a part of an object oriented architecture.
// Sample Url, Watch for Line Breaks
static string pdfUrl = 
  @"http://download.microsoft.com/download/c/a/9/
  ca927411-504e-498a-ad2e-490ca4d9cd27/Journal_4_web.pdf";

// Member variable to store the MemoryStream Data
private MemoryStream pdfMemoryStream;

// Public MemoryStream property containing PDF Data
public MemoryStream PdfMemoryStream 
{
    get 
    {
        // Check to see if the MemoryStream has already been created,
        // if not, then create memory stream
        if (this.pdfMemoryStream == null) 
        {
            WebClient client = new WebClient();    
            try 
            {
                this.pdfMemoryStream = 
                  new MemoryStream(client.DownloadData(pdfUrl));
            } 
            finally 
            {
                client.Dispose();
            }
        }
        return this.pdfMemoryStream;
    }
}

posted on Friday, March 25, 2005 12:11 PM

Home  |   Articles  |   Resume  |   Contact Jay  |   Blog
Site designed and developed by Jay Douglas
© 2001 – 2008
Thursday, August 21, 2008