【发布时间】:2014-08-28 11:21:33
【问题描述】:
在此代码块检查最后一次重新启动 PC 之后,我正在尝试写入文本文件。下面的代码从文本文件中读取,即最后一次重新启动 PC,并从那里确定是否显示启动画面。但是,在此方法运行后,我需要将当前的“系统正常运行时间”写入文本文件。但我不断收到一个错误,说文本文件正在使用中。这让我发疯了。我已确保所有 StreamWriters 和 StreamReaders 都已关闭。我试过使用语句。我试过 GC.Collect。我觉得我已经尝试了一切。
任何帮助将不胜感激。
private void checkLastResart()
{
StreamReader sr = new StreamReader(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
if (sr.ReadLine() == null)
{
sr.Close();
MessageBox.Show("There was an error loading 'System UpTime'. All settings have been restored to default.");
StreamWriter sw = new StreamWriter(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt", false);
sw.WriteLine("Conversion Complete Checkbox: 0");
sw.WriteLine("Default Tool: 0");
sw.WriteLine("TimeSinceResart: 0");
sw.Flush();
sw.Close();
}
else
{
try
{
StreamReader sr2 = new StreamReader(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
while (!sr2.EndOfStream)
{
string strSetting = sr2.ReadLine();
if (strSetting.Contains("TimeSinceResart:"))
{
double lastTimeRecorded = double.Parse(strSetting.Substring(17));
//If the lastTimeRecorded is greater than timeSinceResart (computer has been resarted) OR 2 hours have passed since LVT was last run
if (lastTimeRecorded > timeSinceRestart || lastTimeRecorded + 7200 < timeSinceRestart)
{
runSplashScreen = true;
}
else
{
runSplashScreen = false;
}
}
}
sr2.Close();
sr2.Dispose();
}
catch (Exception e) { MessageBox.Show("An error has occured loading 'System UpTime'.\r\n\r\n" + e); }
}
}
以下是运行上述代码后写入文本文件的示例。无论我打开 StreamWriter 还是使用 File.WriteAllLines,都会立即抛出错误。
StreamWriter sw = new StreamWriter(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
string[] lines = File.ReadAllLines(Path.GetDirectoryName(Application.ExecutablePath) + @"\Settings.txt");
lines[2] = "TimeSinceResart: " + timeSinceRestart;
foreach (string s in lines)
sw.WriteLine(s);
【问题讨论】:
-
在关闭
else块中的第一个实例之前,您正在打开第二个版本的StreamReader。 -
谢谢@entropic 这就是问题所在!我很困惑,因为我在 if 语句打开后立即关闭了 StreamReader。为什么我需要再次关闭它?此外,如果在 if 语句关闭之前 sr 实际上没有关闭,为什么它允许我打开 StreamWriter 的实例来访问该文件?
-
什么意思?如果您在
else块中,则if块中的任何内容都不会执行 - 所以您永远不会真正关闭第一个StreamReader.... -
@entropic 哦,没错!我知道了。谢谢你指出这一切。我希望我能更好地观察那些愚蠢的错误。希望通过练习我会变得更好。
标签: c# .net streamreader streamwriter