I created a WPF app. There is one instance of the app always runs in the background (without a UI) which acts as a service to detect new messages from an API. When it detects a new message, it’ll write the text to the txt file. Another instance when running has UI and it listens to the changes in the file and perform certain action based on the txt file content. The issue I’m encountering is, sometimes the app crashes when I started it (the instance with UI). I suspected it was because of the file so I tried:
- I manually changed the text file but I was not able to save it. Whenever I clicked save, the content does not change. No error message shown either.
- I deleted the text file and run the app again. It worked.
I could not understand what the reason was since there was no error message shown. Any insight would be great. Thank you.
Component used to write the message to txt file:
private Task WriteMessageToFile()
{
try
{
string folderPath = @"C:ProgramDataService";
string filePath = Path.Combine(folderPath, "Message.txt");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
File.WriteAllText(filePath, "some_message_string");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Task.CompletedTask;
}
ViewModel:
public class MainViewVM : ViewModelBase
{
FileWatcherService _fileWatcherService = new();
private string file = "Message.txt";
private string filePath = @"C:ProgramDataService";
// CONSTRUCTOR
public MainViewVM()
{
_fileWatcherService.FileChanged += OnFileChanged;
}
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
HandleNavigation();
}
private void HandleNavigation()
{
try
{
string fullPath = Path.Combine(filePath, file);
if (File.Exists(fullPath))
{
string fileContent = File.ReadAllText(fullPath);
// if there is text in the file, do something, then clear the file
if (!string.IsNullOrEmpty(fileContent))
{
// DO SOMETHING
File.WriteAllText(fullPath, "");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
FileWatcherService:
public class FileWatcherService
{
FileSystemWatcher watcher;
public FileWatcherService()
{
CreateFileWatcher();
}
public event EventHandler<FileSystemEventArgs> FileChanged;
public void CreateFileWatcher()
{
watcher = new FileSystemWatcher(@"C:ProgramDataDPMService", "Message.txt")
{
NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size
};
watcher.Changed += MakeANote;
watcher.Created += MakeANote;
watcher.Deleted += MakeANote;
watcher.Renamed += MakeANote;
watcher.Filter = "*.*";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
}
internal void Dispose()
{
if (watcher != null)
{
watcher.Changed -= MakeANote;
watcher.EnableRaisingEvents = false;
watcher.Dispose();
}
}
private void MakeANote(object sender, FileSystemEventArgs e)
{
FileChanged?.Invoke(this, e);
}
}