StreamWriter 在文件末尾写了一个奇怪的行

Bra*_*ler 0 c# .net-core asp.net-core

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");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 8

出于性能考虑,MemoryStream尝试限制频率的尝试会调整其内部缓冲区的大小。因此,它所做的是,每次写入时,如果它需要扩展其存储容量,它就会调整容量超过所需的大小。这样,下一次写入不应也导致调整大小。

这意味着,例如,它的缓冲区可能是 2048 字节,而您的实际内容只有 1900 字节。最后 148 个字节?这就是你看到的垃圾。

你得到整个缓冲区,这实际上是更长的比你的实际内容。使用ToArray()来代替。这将返回缓冲区的副本,其中仅包含您的实际内容,而不包含剩余的额外空间。