0

I am having an issue with my service when it comes to deleting files after they have been processed from being pulled down from an email account.

Once all the files have all been created by the service I use this code to loop through the files for processing and finally deleting.

string[] fileEntries = Directory.GetFiles(ConfigurationManager.AppSettings["InBoundPath"]);

foreach (string fileName in fileEntries)
{
  FileProcessor fileProcessor = new FileProcessor();
  fileProcessor.ProcessFile(fileName);
}

The deleting works fine until it hits the last file which has a lock on it. It appears a newly created file releases the lock on the old file and a new lock is on the new file.

This is what I am using to create the PDF.

using (FileStream fs = File.Create(newFileName))
{
  byte[] pdfData = email.GetAttachmentData(index);
  fs.Write(pdfData, 0, pdfData.Length);
}

Ideas what might be causing this? I ran Procmon and the error says Sharing Violation. It's probably something simple but I am not seeing what it could be.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Todd
  • 1,780
  • 7
  • 32
  • 54

2 Answers2

0

The exercise of typing this out allowed me to figure it out. I called iTextSharp within a using statement to clean up the file opening and this corrected the issue.

using (iText.PdfReader pdfReader = new iText.PdfReader(originalFilePath))
{
  pageCount = pdfReader.NumberOfPages;
}
Todd
  • 1,780
  • 7
  • 32
  • 54
0

I assume this could be helpful: https://stackoverflow.com/a/2781509

Also try to use FileStream.UnLock for unlocking the file.

Check out this documentation on MSDN for UnLock : http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock(VS.71).aspx

Hope this helps you!

Community
  • 1
  • 1
Eugene
  • 19
  • 1