【发布时间】:2012-01-29 06:49:34
【问题描述】:
我试图在创建文件后删除它,但根本无法删除。 错误消息是它仍在被进程使用。 我正在开发一个 winform 应用程序。
这是我的代码:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.AppendChild(xmlDec);
XmlElement elmRoot = xmlDoc.CreateElement("testConfig");
xmlDoc.AppendChild(elmRoot);
GetConfigTags(xmlDoc, elmRoot, clientToken);
StreamWriter wText =
new StreamWriter(CommonCodeClass.configLocation + "EmailConfig.xml");
xmlDoc.Save(wText);
wText.Flush();
wText.Close();
wText.Dispose();
File.Delete(CommonCodeClass.configLocation + "EmailConfig.xml");
我也试过下面的代码,但同样的错误,文件被另一个进程使用
try
{
File.Delete(CommonCodeClass.configLocation + "EmailConfig.xml");
}
catch //or maybe in finally
{
GC.Collect(); //kill object that keep the file. I think dispose will do the trick as well.
Thread.Sleep(500); //Wait for object to be killed.
File.Delete(CommonCodeClass.configLocation + "EmailConfig.xml"); //File can be now deleted
log.Error(CommonCodeClass.configLocation + "EmailConfig.xml" + " was deleted forcefully as it was being used by the process.");
}
我是否在任何地方都错过了关闭文件?
请帮忙。谢谢。
这里是 getconfigtag 的代码:它只是创建一个要在配置文件中应用的标签。
internal static void GetConfigTags(XmlDocument xmlDoc, XmlElement elmRoot, string clientToken)
{
// Username Element
XmlElement elmUsername = xmlDoc.CreateElement(CommonCodeClass.xml_Username);
XmlAttribute xaUsername = xmlDoc.CreateAttribute("val");
xaUsername.Value = "singleVal";
elmUsername.InnerXml = "";
elmUsername.Attributes.Append(xaUsername);
elmRoot.AppendChild(elmUsername);
}
堆栈跟踪:
在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在 System.IO.File.Delete(字符串路径) 在 C:\Users\ddsds\Documents\Visual Studio 2008\Projects\ShareMgmt\Mgmt\CommonCodeClass.cs 中的 ShareMgmt.CommonCodeClass.EmailTheConfigFile(字符串 userEmail,字符串 clientToken):第 756 行 在 C:\Users\ddsds\Documents\Visual Studio 2008\Projects\ShareMgmt\Mgmt\UsersForm.cs:line 1122 中的 ShareMgmt.UsersForm.btnConfigToAdmin_Click(Object sender, EventArgs e)
【问题讨论】:
-
GetConfigTags 方法有什么作用?此外,您应该养成使用块进行编码的习惯。这样您就不必担心编写 Dispose 调用。
-
您确定错误来自 File.Delete 行吗?它可能来自“new StreamWriter(...)”行吗?
-
代码似乎对我有用。请包括堆栈跟踪。此外,GC 收集不会删除文件锁定。
-
作为一般规则,将
IDisposable对象 (wText) 包装在using语句中。然后对Flush()、Close()和Dispose()的调用都可以消失了。 -
从您的堆栈跟踪来看,您似乎正在尝试通过电子邮件发送 XML 文件。您在使用 MailMessage.Attachments.Add(...) 吗?我想知道这是否保留了参考。