The last character of a text file is not retrieved by System.IO
I tried to write a text file with OutputStream.Write
, but I 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 : all text is one line in a text file.
My text file is somewhat similar to the one above. So can anyone help me?
My code:
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: The full text from the file is now displayed.
UPDATE 2: Updated complete C # code.
UPDATE 3:
Thank you friends for all your efforts! I somehow made it work - the problem was Response.Flush()
and Response.Close()
; as soon as I removed those 2 statements it started working. I do not understand why this problem occurred as I always use Response.Flush()
and Response.Close()
. I never got this error, but this was the first time. If anyone could give me an explanation it would be appreciated. I will reply to @AlexeiLevenkov's post as an answer, since I just tested it again without Response.Flush
and Close()
and it works.
source to share
Stream.CopyTo is easier to match (if you can use .Net 4.0).
using (var stream = System.IO.File.OpenRead(path))
{
stream.CopyTo(outStream);
}
source to share