Access Denied when trying to open with File.OpenRead

1.2k views Asked by At

I have a Windows Service that is processing files. We recently upgraded the framework to 4.5. Around this time we noticed a huge spike in errors often due to 'System.IO.IOException: The process cannot access the file 'D:\Edata\29987082_CREDITNOTE.XML' because it is being used by another process.'

This doesn't happen all the time when processing only about 30%. The service uses a FileInfo object for the filepath and then updates the name with File.Move. It then reuses the FileInfo variable with the new filename. A few lines later it tries to open the file with File.OpenRead and gets the error.

I've seen similar posts where the FileInfo.MoveTo is used. I am not sure if that would help here. I want to know what is causing the error.

Below is the relevant code. fileToProcess is the FileInfo

string DestPath = Path.GetDirectoryName(fileToProcess.FullName);
newpath = string.Format("{0}\\{1}_{2}", DestPath, transmissionid, Path.GetFileName(name));
File.Move(fileToProcess.FullName, newpath);
fileToProcess = new FileInfo(newpath);

LogWriter.Current.WriteLog(LogSeverityType.Info, "Info", string.Format("Tran {0}: Entering CreateCopy method", transmissionID), transmissionID); //This log get written fine

fileToProcess_Stream = File.OpenRead(fileToProcess.FullName);
0

There are 0 answers