0

如果它不存在,我将创建一个文本文件,然后在我向该文件添加文本后立即创建。但是,我的编译器说它正在被另一个进程使用,我认为这是因为它刚刚创建。我怎样才能解决这个问题?

代码摘录-

//If the text document doesn't exist, create it
if (!File.Exists(set.cuLocation))
{
    File.CreateText(set.cuLocation);
}

//If the text file after being moved is empty, edit it to say the previous folder's name
System.IO.StreamReader objReader = new System.IO.StreamReader(set.cuLocation);
set.currentUser = objReader.ReadLine();
objReader.Close();
if (set.currentUser == null)
{
    File.WriteAllText(set.cuLocation, set.each2);
}
4

3 回答 3

5

CreateText方法实际上创建(并返回)一个StreamWriter对象。你永远不会关闭那个流。你想要完成什么?为什么要尝试从空文件中读取?只需保留对StreamWriter您正在创建的内容的引用并将其用于写作。

StreamWriter sw = File.CreateText(set.cuLocation);

然后打电话sw.Write

请参阅http://msdn.microsoft.com/en-us/library/system.io.streamwriter.write.aspx以供参考。

完成后,调用sw.Close

请注意,在您编写时可能会引发异常。这可以防止流被关闭。

解决此问题的一个很好的模式是将 包装StreamWriter在一个using块中。有关更多详细信息,请参阅此问题:是否需要将 StreamWriter 包装在 using 块中?

于 2013-07-24T19:49:28.443 回答
1

不要忘记调用 Close 方法:

if (!File.Exists(set.cuLocation))
{
    File.Create(set.cuLocation)
        .Close();
}
于 2013-07-24T19:52:07.863 回答
0

您可以将其包含在一个using块中,该块会自动为您关闭流:

if (!File.Exists(set.cuLocation))
{
    File.CreateText(set.cuLocation);
}

using(System.IO.StreamReader objReader = new System.IO.StreamReader(set.cuLocation))
{
   set.currentUser = objReader.ReadLine();
}

if (set.currentUser == null)
{
    File.WriteAllText(set.cuLocation, set.each2);
}
于 2013-07-24T19:55:38.637 回答