RickCJ7 0 Newbie Poster

I have searched this forum and see that there are quite a bunch of topics related to files being used by another process. However, none of them seem to fit or work for me. This is my scenario - I have an XML file that is used as a template, it is never modified. I read the XML file, replace some strings in the object, write to a different file name (temp). Then the file is emailed to someone and the temp file is supposed to be deleted, but that is where I get the - cannot delete file - used by another process. Here's parts of my code, opening the template and writing to a different file.

// The template file
string file_template = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["fileTemplateName"]);
// The temp file
string file_output = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["outputFileName"]);
string data;

StreamReader objReader;
objReader = new StreamReader(file_template);

data = objReader.ReadToEnd();

objReader.Close();
objReader.Dispose();

data = data.Replace("FNZZ", fldName.Text);
data = data.Replace("FTDZZ", lblDate.Text);
data = data.Replace("FCEZZ", fldEmail.Text);
data = data.Replace("FCPZZ", fldPhone.Text);
data = data.Replace("FCAZZ", fldAdrress.Text);
data = data.Replace("FPOCCIZZ", fldNameOrg.Text);
data = data.Replace("FDOIZZ", fldToday.Text);
data = data.Replace("FTOIZZ", fldOccur.Text);
data = data.Replace("FNOI1ZZ", fldIncident.Text);
data = data.Replace("FS1ZZ", fldSignature.Text);

// Writes the temp file
File.WriteAllText(file_output, data, Encoding.UTF8);

//Create the mail message 
MailMessage mail = new MailMessage();
mail.Subject = ConfigurationManager.AppSettings["emailSubject"];
mail.Body = ConfigurationManager.AppSettings["emailBody"];
mail.Attachments.Add(new Attachment(file_output));

//the displayed "from" email address - stored in web.config
mail.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["webEmail"]);

//The addresses that will receive the mail - stored in web.config
mail.To.Add(ConfigurationManager.AppSettings["opsEmail"]);

mail.IsBodyHtml = false;
mail.BodyEncoding = System.Text.Encoding.Unicode;
mail.SubjectEncoding = System.Text.Encoding.Unicode;

//create the smtp client
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false;

//Sends the email 
smtp.Send(mail);

// Delete the output file after it has been sent.
File.Delete(file_output); // BOOM! This is where it stops because the file is being used by another process

Response.Redirect("thanks.html");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.