views:

5558

answers:

2

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.

A: 

I would suggest that you are receiving more requests from your client than you think. Check your webserver access log file. The code snippets you are showing seem reasonable, but do not really show enough of the code to explain the problem - you are not showing the right part of the code. Anyway, check the access log or use some kind of tracing.

krosenvold
+4  A: 

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);
}
Jon Skeet