HttpResponse.WriteFile 方法参数 bool readIntoMemory 有什么作用?
MSDN 文档在这方面非常无用,因为我遇到了这种方法并且不完全确定我为什么要这样做或不这样做。
注意:如果有人回答“它会将文件读入内存”而没有进一步解释,将被否决。
MSDN 文档在这方面非常无用,因为我遇到了这种方法并且不完全确定我为什么要这样做或不这样做。
注意:如果有人回答“它会将文件读入内存”而没有进一步解释,将被否决。
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.
区别在于读取文件内容的时间。
如果你通过true
for readIntoMemory
,文件流被打开,读入内存并关闭,所有这些都发生在WriteFile
. 另一方面,如果您通过false
,文件流将再次打开和关闭而不读取(只是为了验证文件是否存在)。相反,关于要写入哪个文件的信息被传递到某个内部缓冲区(使用 internalHttpWriter.WriteFile
方法)。稍后(可能在刷新响应时,但我还没有验证这一点),将读取文件的内容。
考虑以下代码:
protected void Page_Load(object sender, EventArgs e)
{
Response.WriteFile(@"C:\myFile", false);
System.IO.File.Move(@"C:\myFile", "C:\myFile2");
Response.End();
}
请注意,您的浏览器不会收到响应,即在Response.End
. 设置readIntoMemory
为true
避免此问题。
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.