We are receiving files in FileSystemWatcher folder very frequently because of that InternalBufferSize limit is getting exceeded and files are being missed. I am using the max limit 65536 allowed for InternalBufferSize.
I have also gone through many questions related to this, but could not find appropriate solution.
My Concern is:
Can we optimize this code more accurately?
If not, Is there any other way to watch the file?
private void FileWatcher() { try { f_Watcher = new System.IO.FileSystemWatcher(); f_Watcher.Path = InFolder; f_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; f_Watcher.Filter = "*.*"; f_Watcher.IncludeSubdirectories = true; f_Watcher.Created += new FileSystemEventHandler(OnChanged); f_Watcher.EnableRaisingEvents = true; f_Watcher.InternalBufferSize = 65536; f_Watcher.Error += new ErrorEventHandler(LogBufferError); } catch (Exception) { throw; } }
OnChanged Method code block:
private void OnChanged(object sender, FileSystemEventArgs e)
{
try
{
System.Threading.Thread.Sleep(2000);
InFolder = ConfigurationManager.AppSettings["InputPath"].ToString();
DirectoryInfo getInDirectoryFile = new DirectoryInfo(InFolder);
if (!getInDirectoryFile.Exists)
{
getInDirectoryFile.Create();
}
fileExt = ConfigurationManager.AppSettings["fileExt"].ToString();
//string file_path = getInDirectoryFile.ToString();
string file_path = Path.GetDirectoryName(e.FullPath);
string fname = e.Name.ToString();
string[] file = Directory.GetFiles(file_path, fileExt); // GET ONLY .txt File
if (file.Length > 0)
{
HLFile_Process.ProcessHL7File(file_path, fname); //Process HL7 files
}
else
{
MIEventLogs.WriteLog("Currently there is no file at " + getInDirectoryFile + DateTime.Now.Month.ToString() +
"-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Year.ToString() + "-" +
DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" +
DateTime.Now.Second.ToString());
}
}
catch (Exception ex)
{
MIEventLogs.WriteLog(ex.ToString() + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" +
DateTime.Now.Year.ToString() + "-" + DateTime.Now.Hour.ToString() + ":" +
DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString());
}
finally
{
MIEventLogs.WriteLog("MI File Process END: " + DateTime.Now.Month.ToString() + "_" +
DateTime.Now.Day.ToString() + "_" + DateTime.Now.Year.ToString() + "_" +
DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" +
DateTime.Now.Second.ToString());
}
}
OnChangeddoing? As alternative you can maintain your internal queue (and post there inOnChanged) and process it in parallel.