I'm trying to have two applications communicate trough a simple text file. My problem is that I have a Windows Store App which writes like so:
byte[] data = Encoding.UTF8.GetBytes(toSend);
var folder = KnownFolders.PicturesLibrary;
var file = await folder.GetFileAsync("orders");
using (var stream = await file.OpenStreamForWriteAsync())
{
await stream.WriteAsync(data, 0, data.Length);
}
The writing happens as expected and the line is in the format I need it. I have a FileSystemWatcher in the second app which is a simple console app. The watcher is set like this:
FileSystemWatcher watcher;
watcher = new FileSystemWatcher(path);
watcher.Filter = "orders";
watcher.NotifyFilter = NotifyFilters.LastWrite;
var result = watcher.WaitForChanged(WatcherChangeTypes.Changed);
I tried to set the filter with size just as a test. If the event is called, I read the file like this:
private String readFile()
{
FileStream fileStream = new FileStream(this.path + @"\orders", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader fileReader = new StreamReader(fileStream);
String line = "";
line = fileReader.ReadLine();
return line;
}
So fairly simple usage I'd think. My problem is that the FileSystemWatcher catches the modification when my other app opens the text file therefore it reads the previous line intended.
Does anyone have an idea how to "wait" for the file to be written?
Thanks!
SOLVED Thanks to you guys. I tried looping by creating a small recursive function and I noticed that I need at most two loops for the correct line to be created so everything is fine. Thank you again.