When using the FileInfo object I am trying to copy files from one folder to another. After the copy process is complete, I delete the file in the original folder. After viewing the logs I see this error every once in awhile.
The process cannot access the file [filename] because it is being used by another process
I have tried numerous pieces of code (GC.collect, fi.refresh, checking for the file being locked, etc ...) and I still get this error and even more frequently. Here is some of the code. The project is a windows service.
private void fsw_Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
FileInfo fi = new FileInfo(e.FullPath);
fi.Refresh();
if(!fi.Exists) return;
try
{
string trans_id = this.MakeTransactionID();
this.LogReceiptOfFile(fi.Name,trans_id);
if(fi.Name!="heartbeat.csv")
{
fi.Refresh();
this.CopyToArchive(fi,trans_id);
}
fi.Refresh();
this.CopyToOut(fi,trans_id);
fi.Refresh();
this.DeleteFromIn(fi,trans_id);
}
catch(Exception ex)
{
this.LogError("fsw_Watcher_Changed",ex);
}
finally
{
fi = null;
GC.Collect();
}
}
private void LogReceiptOfFile(string fileName,string trans_id)
{
Log myLog = new Log(LOGPATH);
myLog.WriteToProcessLog(trans_id,1,"Received","MCGWare",fileName);
myLog = null;
}
private void LogError(string func,Exception ex)
{
Log myLog = new Log(LOGPATH);
myLog.WriteLogMessage(func,ex.Message + "\n" + ex.StackTrace,1);
myLog = null;
EventLog elog = new EventLog();
elog.Source = "Application";
elog.Log = "Application";
elog.WriteEntry("Error reported in fsw_Watcher_Changed function. Read SDX log files for details.",
System.Diagnostics.EventLogEntryType.Error);
elog = null;
}
private void CopyToArchive(FileInfo fi,string trans_id)
{
Log myLog = new Log(this.processPath);
string fileName =
this.archivePath + "\\" +
this.MakeFileName(fi.Name.Replace(".csv",""));
try
{
fi.CopyTo(fileName,true);
myLog.WriteToProcessLog(trans_id,1,"Copy",fi.FullName,fileName);
}
catch(Exception ex)
{
this.LogError("CopyToArchive",ex);
myLog.WriteToProcessLog(trans_id,0,"Copy",fi.FullName,fileName);
}
finally
{
myLog = null;
}
}
private void CopyToOut(FileInfo fi,string trans_id)
{
Log myLog = new Log(this.processPath);
string fileName = this.outPath + "\\" + fi.Name;
try
{
fi.CopyTo(fileName,true);
myLog.WriteToProcessLog(trans_id,1,"Copy",fi.FullName,fileName);
}
catch(Exception ex)
{
this.LogError("CopyToOut",ex);
myLog.WriteToProcessLog(trans_id,0,"Copy",fi.FullName,fileName);
}
finally
{
myLog = null;
}
}
private void DeleteFromIn(FileInfo fi,string trans_id)
{
Log myLog = new Log(this.processPath);
try
{
fi.Delete();
myLog.WriteToProcessLog(trans_id,1,"Delete",fi.FullName,"");
}
catch(Exception ex)
{
this.LogError("DeleteFromIn",ex);
myLog.WriteToProcessLog(trans_id,0,"Delete",fi.FullName,"");
}
finally
{
myLog = null;
}
}