简体   繁体   中英

StreamWriter is writing a weird line at the end of a file

I'm using a StreamWriter to write a string to memory and then return it as a file via an IActionResult in an ASP.Net Core Web API, and I'm running into a weird issue where I'm getting a line of indecipherable characters at the end of the output file...

Here's an image of what I'm talking about:

在此处输入图像描述

The text on line 513 is not supposed to be there... I'm thinking it has something to do with encoding, but I don't know much about encoding or text, so I'm hoping someone more knowledgeable can help out...

Here is my code:

    [HttpGet("download/{fileId}")]
    public IActionResult DownloadFile(int fileId)
    {
        if (!_fileRepository.FileExists(fileId))
            return NotFound();

        var file = _fileRepository.GetFile(fileId);

        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        string BAIFile = ParseModelToFile(file);

        using (MemoryStream ms = new MemoryStream())
        {
            using (var sw = new StreamWriter(ms, new UnicodeEncoding()))
            {
                sw.Write(BAIFile);
                sw.Flush();
                sw.Close();

                return File(ms.GetBuffer(), "text/plain", DateTime.Now.ToShortDateString() + ".BAI");
            }
        }
    }

For the sake of performance, the MemoryStream attempts to limit the frequency it resizes its internal buffer. So, what it does is, each time you write, if it needs to expand its storage capacity, it will resize that capacity more than is needed. This way, the next write shouldn't also result in a resize.

This means, for example, its buffer could be 2048 bytes, while your actual content is only 1900 bytes. That last 148 bytes? That's the garbage you are seeing.

You are getting the entire buffer, which is actually longer than your actual content. Use ToArray() instead. This will return a copy of the buffer, containing only your actual content, and not the leftover extra space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM