Link to home
Start Free TrialLog in
Avatar of JoeD77
JoeD77

asked on

Downloading a file and holding it in memory in c#

Hello,
I am trying to download a remote file and hold it in memory; I am currently working with this code (listed) with no success. Hoping someone could give me some insight, example code would be very appreciated.
static void Main(string[] args)
        {
            byte[] downloadedData;
            downloadedData = new byte[0];
            WebRequest req = WebRequest.Create("http://www.nsrdl.com/apps/msizap.exe");
            WebResponse response = req.GetResponse();
            Stream stream = response.GetResponseStream();

            byte[] buffer = new byte[1024];

            int dataLength = (int)response.ContentLength;
            Console.Write(dataLength);


            MemoryStream memStream = new MemoryStream();
            while (true)
            {
                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                memStream.Write(buffer, 0, bytesRead);
                downloadedData = memStream.ToArray();

            }

            downloadedData = memStream.ToArray();

            stream.Close();
            memStream.Close();
}

Open in new window

Avatar of AlfredRobot
AlfredRobot
Flag of Canada image

Avatar of rockiroads
What about using the WebClient object? http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=115
I dont know about exe's though. Will give it a try
Avatar of JoeD77
JoeD77

ASKER

All of those deal with writing the downloaded data directly to disk. I would like to hold it in memory. Any possible solutions?
ASKER CERTIFIED SOLUTION
Avatar of rockiroads
rockiroads
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of JoeD77

ASKER

Thanks, rockiroads

Before reading your comment I was able to successfully store the file in memory without having it touch disk with this code (listed)

Now my problem is the downloaded data is not in binary form, hence it is unexecutable

Any way to convert "line" into a binary data type?
            System.Net.WebClient Client = new WebClient();
            Stream strm = Client.OpenRead("http://www.nsrdl.com/apps/msizap.exe");
            StreamReader sr = new StreamReader(strm);
            
            
            string line;
            while(sr.Peek() >= 0)
            {
                line = sr.ReadLine();
                line += sr.ReadLine();
            }
            strm.Close();

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial