views:

26

answers:

3

What does HttpResponse.WriteFile Method parameter bool readIntoMemory do?

The MSDN documentation is very unhelpful in this regard as I came across this method and wasn't exactly sure why I'd want to do this or not do this.

Note: should anyone respond with "well it reads the file into memory" with no further explanation will be downvoted.

+2  A: 

Looking with Reflector, it seems to indicate whether the file should be buffered in memory before being written to the response.

The file is opened using a FileStream and then if that boolean flag is set, it first reads the file into a byte array before writing that array to the response using WriteBytes.

If the flag is not set then the file is written to the response using WriteFile.

Both of the former scenarios make the assumption that a HttpWriter is being used. If that's not the case, then WriteStreamAsText is used.

Russ Cam
+3  A: 

Russ is right about the behavior - the reason you would use it is to avoid keeping the file open/locked - especially since the client might be slow, or time out, it may be more preferable to make the memory tradeoff and buffer the file into memory, so this bool lets you skip having to ReadAllBytes into a buffer on your own and then write the resulting buffer.

James Manning
+1 - for the why
Russ Cam
+2  A: 

The difference is the time when the file's contents are read.

If you pass true for readIntoMemory, the file stream is opened, read into memory and closed, and all of that happens during WriteFile. On the other hand, if you pass false, the file stream is opened and closed again without reading (just to verify that the file exists). Instead, the information about which file to write is passed into some internal buffer (using the internal HttpWriter.WriteFile method). Later (probably when the response is flushed, but I haven't verified this), the file's contents will be read.

Consider the following code:

protected void Page_Load(object sender, EventArgs e)
{
    Response.WriteFile(@"C:\myFile", false);
    System.IO.File.Move(@"C:\myFile", "C:\myFile2");
    Response.End();
}

Note that your browser won't receive a response, i.e., something goes terribly bad during Response.End. Setting readIntoMemory to true avoids this problem.

Heinzi