As far as I know there is no way to avoid the file system watcher from firing multiple events, so I have used work-around to solve this issue.
You can try something like this. It is not foolproof if you have a lot of updates to multiple files. In that case you might have to use a list.
private object lockObject = new object();
private string fileNameInUse = "";
private void OnChanged(object source, FileSystemEventArgs e)
{
lock (lockObject)
{
if (fileNameInUse == e.FullPath)
{
fileNameInUse = "";
return;
}
fileNameInUse = e.FullPath;
try
{
NetworkStream networkStream = clientSocket.GetStream();
line = new string[] { };
using(FileStream fs = new FileStream(e.FullPath,FileMode.Open,FileAccess.Read))
using (StreamReader sr = new StreamReader(e.FullPath))
{
String [] line = sr.ReadLine().Split(',');
for (int p = 0; p < line.Length; p++)
{
b = Encoding.ASCII.GetBytes(line[p]);
networkStream.Write(b, 0, b.Length);
}
sr.Close();
sr.Dispose();
fs.Flush();
}
}
catch { }
}
}
I hope I am wrong and there is a better solution.
[UPDATE]
An alternative solution
private object lockObject = new object();
private void OnChanged(object source, FileSystemEventArgs e)
{
watcher.EnableRaisingEvents = false;
lock (lockObject)
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
line = new string[] { };
using(FileStream fs = new FileStream(e.FullPath,FileMode.Open,FileAccess.Read))
using (StreamReader sr = new StreamReader(e.FullPath))
{
String [] line = sr.ReadLine().Split(',');
for (int p = 0; p < line.Length; p++)
{
b = Encoding.ASCII.GetBytes(line[p]);
networkStream.Write(b, 0, b.Length);
}
sr.Close();
sr.Dispose();
fs.Flush();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
watcher.EnableRaisingEvents = true;
}
}
}