I am trying to delete a file after i create it but simply cannot.
The error message is that it is still being used by the process.
I am working on a winform application.
here is my code:
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");
I have also tried the code below but the same error, File being used by another process
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.");
}
Am i missing a close of file anywhere?
Please help. Thanks.
here is the code for getconfigtag: it just creates a tags to be applied in the config file.
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);
}
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.Delete(String path)
at ShareMgmt.CommonCodeClass.EmailTheConfigFile(String userEmail, String clientToken) in C:\Users\ddsds\Documents\Visual Studio 2008\Projects\ShareMgmt\Mgmt\CommonCodeClass.cs:line 756
at ShareMgmt.UsersForm.btnConfigToAdmin_Click(Object sender, EventArgs e) in C:\Users\ddsds\Documents\Visual Studio 2008\Projects\ShareMgmt\Mgmt\UsersForm.cs:line 1122
“Am I missing a close of file anywhere?” You can be sure the file gets closed by using a ‘using’ statement.
This code works for me, but so does a variation of your original, so beyond that, I’m not quite sure what the issue is.
Addendum:
It appears—by your stack trace—that you’re trying to email an XML file. If that’s the case, and you’re using SmtpClient, you don’t even need to write the XML document to a file.