记事本仅获取 Streamwriter 文本文件生成器上应为 1000 个条目的 768 个条目

Notepad only gets 768 entries of what should be 1000 entries on a Streamwriter text file generator

我正在制作一个简单的程序,它应该获取一个包含 2 列的 1000 个条目的数组并将其转换为文本格式,然后将其输出到一个文件。
有些奇怪的事情发生了。该文件仅接收 950 或 768 个条目行,而不是应有的 1000 个。我的实际数组实际上是一个点数组,用于 DrawLine 之类的东西,但为了演示错误,我只使用了一个直接向上计数的数组。

请问问题出在哪里。是因为添加到文件时缓冲区的最大大小吗?仅仅是因为文本文件有最大尺寸吗?是因为实际文件是正确的,但记事本只让我看到文件的有限部分吗?我应该扔掉这台电脑再买一台吗?

如有任何帮助,我们将不胜感激。为什么停在768?这个数字似乎是任意的。 如您所见,它是一个 WindowsForm。

private void GcodeSave_Click(object sender, EventArgs e)
    {

        DialogResult result;  //Specifies identifiers to indicate the return value of a dialog box
        string fileName;

        using (SaveFileDialog fileChooser = new SaveFileDialog()) 
        {
            fileChooser.CheckFileExists = false;
            result = fileChooser.ShowDialog();
            fileName = fileChooser.FileName;
        }

        if(result==DialogResult.OK)
        {
            if (fileName == string.Empty)
                MessageBox.Show("Invalid File Name", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                try
                {
                    FileStream output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);

                    fileWriter = new StreamWriter(output);
                    for (int t = 0; t <= 1000; t++)
                    {
                        fileWriter.WriteLine("{0}   {1}", t, t);

                    }

                    fileWriter.WriteLine("There were {0} elements in spiroArray", numberOfPoints);

                    //It only goes up to 950 in the text file.
                    //With word wrap off it goes to 764 and then it gets 1/3 way through 764 and writes 76
                }
                catch(IOException)
                {
                    MessageBox.Show("Error opening file", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }

您需要关闭 StreamWriter。

FileStreamStreamWriter 都在内部使用缓冲区。这些将在显式调用(通过 Flush)或 closed/disposed.

时刷新

由于这些对象使用外部资源并实现 IDisposable,因此它们都应该被处理掉。最常见的模式是使用 using 语句:

using (var stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
using (var writer = new StreamWriter(stream))
{
     //use writer here
}

一旦释放,缓冲区中的数据将被写入文件并释放文件句柄。