Reputation: 465
I tried to write a text file using OutputStream.Write
but, I've noticed that the last character of the file is not being sent.
Whether the file is 6KB or 242KB, the last character is skipped.
AwAIB0UfFlJTSTNABEQWGgMVAhNFBkVeKgVTSx4LCVQMBUUQRUMwBVFTGwcAEAASRRNTBipNQQMFDREYB
BUAH0VIKgVLRVccCRFFGRcbR08wREgDEQENEUkCDRNOTX5cS1ZXHgQGHFYIB0NOfgUIAwMABFQABBcdUg
YpRFcDHgZBAA0TRTEDBj1KQEZXREEdRRIKHFQGK0tARgUbFRULEkUFSF9+R1FXVxwJEUUkAAFQSTBWQQ0
xBBQHDV5MUkFIOgV2RgQYDhoWE0sxTEktQAwKVx8AB0UCDRcAQyxXS1FZSBUcBAIWUldDN1dAAxEHE1QI
E0UTTkJ+TARAFgYVVBAYARdSVSpESkdXAAAcBFg=
Note: whole text is one line in the text file.
My text file is somewhat similar to the above. So can anyone help me out?
var path = Request.QueryString["path"];
path = Server.MapPath(Url.Content("~/Files/" + path + "/somefile.txt"));
Response.Buffer = false;
Response.ContentType = "text/plain";
FileInfo file = new FileInfo(path);
int len = (int)file.Length, bytes;
Response.AppendHeader("content-length", len.ToString());
byte[] buffer = new byte[1024];
Stream outStream = Response.OutputStream;
using (Stream stream = System.IO.File.OpenRead(path))
{
while (len > 0 && (bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytes);
len -= bytes;
}
}
Response.Flush();
Response.Close();
UPDATE 1: Now shows the complete text from the file.
UPDATE 2 : Updated the complete C# code.
UPDATE 3:
Thanks, my friends, for all your efforts! I somehow made it work - the problem was Response.Flush()
and Response.Close()
; once I removed these 2 statements it started working. I don't understand why this problem occurred as I always use Response.Flush()
and Response.Close()
. I never received this kind of error but this was the first time. If anyone could give me an explanation, it would be appreciated. I will mark @AlexeiLevenkov's post as the answer, as I just tested it again without the Response.Flush
and Close()
and it is working.
Upvotes: 4
Views: 260
Reputation: 100620
Stream.CopyTo is easier approaach (as long as you can use .Net 4.0).
using (var stream = System.IO.File.OpenRead(path))
{
stream.CopyTo(outStream);
}
Upvotes: 2