以下代码不会写入文本文件。根据我的知识,不确定为什么,正如我完全按照我的书。运行时不会抛出任何错误,程序运行成功。文件路径正确,提到的文件当前未打开
String databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";
StreamWriter Writer = new StreamWriter(new FileStream(databasePath,
FileMode.Append, FileAccess.Write));
Writer.WriteLine("Test");
Console.ReadKey();
Writer.Close();
答案 0 :(得分:3)
如果你想追加,只需AppendAllText:
string databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";
File.AppendAllText(databasePath, "Test");
如果您坚持Writer
在 Console.ReadKey
之前关闭它(当您检查文件时)
// first write into the file
//DONE: do not close IDisposable explicitly, but wrap them into "using"
using (StreamWriter Writer = new StreamWriter(
new FileStream(databasePath,
FileMode.Append,
FileAccess.Write))) {
Writer.WriteLine("Test");
}
// ... then stop and check file's content
Console.ReadKey();
答案 1 :(得分:1)
Console.ReadKey();
Writer.Close();
请在Console.ReadKey();
之后移动Writer.Close();
行。函数 ReadKey 保存执行,并且除非调用 Write.Close 函数,否则不会将内容写入文件。所以你的代码应该是这样的:
String databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";
StreamWriter Writer = new StreamWriter(new FileStream(databasePath,
FileMode.Append, FileAccess.Write));
Writer.WriteLine("Test");
Writer.Close();
Console.ReadKey();
答案 2 :(得分:0)
虽然您的代码应该按照书面形式运行,但可能存在缓存问题:
我建议您在writer.Flush()
之前添加writer.Close()
。
除此之外,您应该using
StreamWriter
而不仅仅是创建它以确保它被正确处理。
组合这两点将呈现以下代码:
String databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";
using (StreamWriter writer = new StreamWriter(new FileStream(databasePath,
FileMode.Append, FileAccess.Write)))
{
writer.WriteLine("Test");
Console.ReadKey();
writer.Flush();
//writer.Close(); this may or may not be needed.
}