Convert MemoryStream to FileStream creates hundreds of identical files?

26,753

It's not at all clear why you'd get multiple files, but you should be able to get some information based on the filenames - each one would correspond to a value of newFile.

I note that you're not closing your file stream, by the way. Using File.WriteAllBytes is a much simpler way of achieving your goal, and doesn't require you to close anything:

byte[] data = stream.ToArray();
File.WriteAllBytes(newFile, data);

An alternative is to still use a FileStream (with a using statement) but use MemoryStream.WriteTo to avoid the call to ToArray which has to copy all the data:

using (FileStream fs = File.Create(newFile))
{
    stream.WriteTo(fs);
}
Share:
26,753
mickyjtwin
Author by

mickyjtwin

.NET Software Engineer

Updated on July 09, 2022

Comments

  • mickyjtwin
    mickyjtwin almost 2 years

    I am accessing a httpwebrequest that returns a pdf file as the response. I am reading that response into a memory stream, and later on converting to a file. The problem is, is that hundreds of files are being created. Not sure why, I've tried many ways, and all do the same... This is the first method which returns the memorystream.

            MemoryStream memStream = new MemoryStream();
            byte[] buffer = new byte[2048];
    
            int bytesRead = 0;
            do
            {
                bytesRead = _ResponseStream.Read(buffer, 0, buffer.Length);
                memStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
    

    Second to convert to FileStream...

                byte[] data = stream.ToArray();
    
                FileStream fs = new FileStream(newFile, FileMode.CreateNew);
                fs.Write(data, 0, data.Length);
    

    Any ideas?

    EDIT TO ADD MORE CODE...

        public MemoryStream GetToStream()
        {
            if (_Req == null)
                throw new Exception("HttpWebRequest is not initialised");
    
            GetResult(_Req);
    
            MemoryStream memStream = new MemoryStream();
            byte[] buffer = new byte[2048];
    
            int bytesRead = 0;
            do
            {
                bytesRead = _ResponseStream.Read(buffer, 0, buffer.Length);
                memStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
    
            _ResponseStream.Close();
    
            if (memStream.Length > 0)
                return memStream;
            else return null;
        }
    

    newFile is the mapped path to the server of the file to create.

                byte[] data = stream.ToArray();
    
                FileStream fs = new FileStream(newFile, FileMode.Create);
                fs.Write(data, 0, data.Length);
                fs.Close();
    

    I've tried stream.WriteTo(fs), and same thing occurs. Quite bizzare.