我是C#的初学者并且正在努力练习,不管怎样,我可以使用StreamWriter和File.CreateText将其写入项目的Bin文件夹中的txt文件,但是当我尝试添加路径并附加它我得到一个文件,但没有写入它。
我只是使用WinFormApp
try
{
string mypath = @"C:\Temp\Rocket League Tracker.txt";
StreamWriter RocketLeagueTrackerFile;
RocketLeagueTrackerFile = File.CreateText(mypath);
RocketLeagueTrackerFile.WriteLine("Rocket League Tracking");
File.AppendAllText(mypath, MyGameResult + Environment.NewLine);
RocketLeagueTrackerFile.Close();
}
catch
{
}
答案 0 :(得分:2)
您应该使用using语句。 File.CreateText
是锁定文件。
using(RocketLeagueTrackerFile = File.CreateText(mypath))
{
RocketLeagueTrackerFile.WriteLine("Rocket League Tracking");
}
File.AppendAllText(mypath, MyGameResult + Environment.NewLine);
答案 1 :(得分:2)
当您调用 File.CreateText 时,您正在获取该文件的锁定。
以下对 File.AppendAllText 的调用不使用File.CreateText中返回的StreamWriter,但它再次尝试获取同一文件的锁定。
这会导致异常(IOException)但您无法看到它,因为您添加了一个空的try / catch。
永远不要无理由地使用空的try / catch,因为您隐藏了异常情况,并且您的程序可能会崩溃,而无需在用户桌面上进行说明。
或者你花了很多时间搜索一个神秘的bug并需要调用SO(就像这里)。
如果您确实需要向用户显示消息,那么
.....
catch(Exception ex)
{
MessageBox.Show("Unexpected Error:" + ex.Message);
// Rethrow the exception to upper layers....
throw;
}
说,你不需要File.CreateText,因为根据MSDN的File.AppendAllText
打开文件,将指定的字符串附加到文件中,然后 关闭文件。如果该文件不存在,则此方法创建一个 文件,将指定的字符串写入文件,然后关闭文件。
string mypath = @"C:\Temp\Rocket League Tracker.txt";
string title = "Rocket League Tracking";
File.AppendAllText(mypath, title + Environment.NewLine +
MyGameResult + Environment.NewLine);
如果您需要始终使用该名称覆盖以前的文件,请将File.AppendAllText替换为File.WriteAllText。
答案 2 :(得分:0)
您也可以使用:
File.WriteAllText(mypath ,"Rocket League Tracking");