【发布时间】:2010-12-21 22:03:44
【问题描述】:
我正在编写一个操作文本文件的应用程序。我的函数的前半部分读取文本文件,而后半部分写入(可选)同一个文件。虽然我在打开 StreamWriter 对象之前在 StreamReader 对象上调用了.close(),但我仍然得到一个IOException: The process cannot access the file "file.txt" because it is being used by another process.
如何强制我的程序在继续之前释放文件?
public static void manipulateFile(String fileIn, String fileOut,String obj)
{
StreamReader sr = new StreamReader(fileIn);
String line;
while ((line = sr.ReadLine()) != null)
{
//code to split up file into part1, part2, and part3[]
}
sr.Close();
//Write the file
if (fileOut != null)
{
StreamWriter sw = new StreamWriter(fileOut);
sw.Write(part1 + part2);
foreach (String s in part3)
{
sw.WriteLine(s);
}
sw.Close();
}
}
【问题讨论】:
-
显示您的代码。这是您获得特定场景相关帮助的唯一方法。
-
就在我的脑海中,您是调用了
Dispose()方法,还是将您的StreamReader包装在using { }块中?处理它可能会强制释放文件。 -
@Coding Gorilla,你不应该手动调用
Dispose,在处理一次性资源时你应该总是使用using块。 -
@Darin 我不同意你永远不应该手动调用它。除非有充分的理由,否则不应手动调用它。例如,如果您已经有一个 try/catch 块(例如该文件可能不存在),则在其周围放置
using没有意义,只需将dispose放在finally -
@Darin Dimitrov:为什么会这样?那么,您将如何在另一个上下文中释放资源?在我看来,这样的一般规则(即永远不要显式调用
Dispose)毫无意义。
标签: c#