创建后编辑文本文件

The*_*ark 0 c#

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

代码摘录 -

//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);
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*ski 5

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

StreamWriter sw = File.CreateText(set.cuLocation);
Run Code Online (Sandbox Code Playgroud)

然后打电话sw.Write

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

完成后,请致电sw.Close.

请注意,在您编写时可能会发生异常抛出.这可以防止流被关闭.

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