C# FileStream.WriteLine() 未写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15452866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:53:09  来源:igfitidea点击:

FileStream.WriteLine() is not writing to file

c#file-iostreamtext-files

提问by Lorenzo Verri

I am trying to make a simple software which stores data in a TXT log file. This is my code

我正在尝试制作一个简单的软件,将数据存储在 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();
}

What I achieved is: the file gets created, but nothing gets written in it. I checked a lot of posts but I could not find any particular help.

我实现的是:文件被创建,但没有写入任何内容。我检查了很多帖子,但找不到任何特别的帮助。

回答by Davin Tryon

Adding a call to Flushthe stream works. This is because you are wrapping the FileStream. StreamWriterwill write to the FileStream, but you need to indicate when to send the Streamto the actual file. Also, you can exchange your try finallywith a using:

添加Flush对流的调用有效。这是因为您正在包装FileStream. StreamWriter将写入FileStream,但您需要指明何时将 发送Stream到实际文件。此外,您可以用以下方式交换您try finallyusing

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");
}

回答by Steve

Enclose your StreamWriterin an using block to be sure that everything is correctly closed at the end of the file usage, also I don't think you need to create a FileStreamfor this to work.

将您的代码包含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");
}

Note that the StreamWriterhas a constructor that accepts two parameters, the name of the file to create/open and a flag to indicate that the file should be opened in append mode or overwritten See StreamWriter docs

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

回答by theMayer

Indeed, Flush() is the answer; however, I would use File.WriteAllLines()instead.

事实上,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");
}

回答by Herdo

Try using this - just replace the array:

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

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");
}

回答by NSGaga-mostly-inactive

Always use using(as mentioned already) and you won't run into problems (or have to think about it)...

始终使用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");
}  

(also you could have closed the writer instead of filestream which should've worked)

(你也可以关闭编写器而不是应该工作的文件流)

The problem is as I far as I can tell...

据我所知,问题是......

FileStream.Closeis actually Stream.Close- and that calls Disposebut it ain't virtual, so does some general cleanup.

FileStream.Close实际上是Stream.Close- 这会调用,Dispose但它不是虚拟的,一些常规清理也是如此。

FileStream.Disposewhich is called implicitly when you use using- does specific Flushand then Close/Dispose - so does proper specific cleanup.

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

You can avoid any of that via usingas that is generally recommended pattern (and frankly never got me into any of these)

你可以避免任何一种通过,using因为这是通常推荐的模式(坦率地说,我从未让我进入任何这些模式)