FileStream.WriteLine()没有将内容写入文件

7
我正在尝试制作一个简单的软件来将数据存储在TXT日志文件中。 以下是我的代码。
FileStream fs = null;
StreamWriter fw = null;
try
{
    fs= new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    fw = new StreamWriter(fs);
    fw.Write("sadadasdsadsadsadas");

    for (int i = 0; i < AnimalShelter.AnimalList.Count; i++)
    {
        fw.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
        Console.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
    }
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}
finally
{
    if (fs!= null) fs.Close();
    //  if (fw != null) fw.Close();
}

我所达到的是:文件已创建,但其中未写入内容。我查看了很多帖子,但没有找到特别有用的帮助。

3
首先,try/finally块并不需要,你可以使用using块代替。 - antonijn
3
你可能需要清空 StreamWriter:fw.Flush() - Davin Tryon
StreamWriter有一个构造函数,它接受一个字符串——文件路径和一个布尔值——设置为true以进行追加。这将帮助您成功地避免错误。 - Hans Passant
你需要刷新并关闭流以确保所有数据都被写入。请查看这里:http://msdn.microsoft.com/zh-cn/library/system.io.streamwriter.close.aspx - CodeChops
6个回答

7

添加一个调用Flush的语句可以解决问题。这是因为你正在包装FileStreamStreamWriter将写入FileStream,但是你需要指示何时将Stream发送到实际文件中。此外,你可以使用using替换try finally

try
{
    using (var fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        using (var fw = new StreamWriter(fs))
        {
            fw.Write("sadadasdsadsadsadas");

            for (int i = 0; i < AnimalShelter.AnimalList.Count; i++)
            {
                fw.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
                Console.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");

            }
            fw.Flush(); // Added
        }
    }
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}

6

将您的StreamWriter放入using块中,以确保在文件使用结束时正确关闭所有内容,此外我认为您不需要创建一个FileStream来使其工作。

try
{
    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "textme.txt")
    using(fw = new StreamWriter(fileName, true))
    {
         ......
    }
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}

请注意,StreamWriter有一个构造函数,它接受两个参数:要创建/打开的文件名和一个标志,指示文件应在追加模式下打开还是覆盖模式下打开。 请参阅StreamWriter文档

2

一定要使用using(如之前所提到的),这样就不会出现问题(也不用考虑它)...

using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
using (StreamWriter fw = new StreamWriter(fs))
{
    fw2.Write("sadadasdsadsadsadas");
}  

问题在于,据我所知...

FileStream.Close 实际上是 Stream.Close - 它调用了 Dispose ,但它不是虚拟的,因此进行了一些常规清理。

FileStream.Dispose 在使用 using 时会被隐式调用 - 它执行特定的 Flush 然后执行 Close/Dispose - 因此进行适当的特定清理。

您可以通过使用 using 来避免任何这些问题,因为这通常是推荐的模式(而且说实话从来没有让我遇到过这些问题)。

(您也可以关闭 writer 而不是 FileStream,这应该也能正常工作)


1

确实,Flush() 是答案;不过我会使用 File.WriteAllLines()

try
{
    var fileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/textme.txt";
    var lines = AnimalShelter.AnimalList.Select(o=> "<chipNr>" + o.ChipRegistrationNumber + "</chipNr>");
    File.WriteAllLines(fileName, lines);
    foreach(var line in lines)
        Console.WriteLine(line);
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}

0

尝试使用这个 - 只需替换数组:

try
{
    using (Stream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        using (StreamWriter sw = new StreamWriter(fs))
        {
            int[] test = new int[] { 0, 12, 23, 46 };
            sw.Write("sadadasdsadsadsadas");
            for (int i = 0; i < test.Length; i++)
            {
                sw.WriteLine("<chipNr>" + test[i] + "<chipNr>");
                Console.WriteLine("<chipNr>" + test[i] + "<chipNr>");
            }
            sw.Close();                    
        }
        fs.Close();
    } 

}
catch (IOException)
{
    MessageBox.Show("ERROR THROWN");
}

0
如codechops所提到的,close()对我有用。我在最后一次写入时遇到了问题,使用文件流的close()方法解决了这个问题。
基本上,需要将流中的数据刷新到文件中,以使写入正常工作。

你的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人能够确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接