- Я вручную изменил текстовый файл, но не смог его сохранить. Всякий раз, когда я нажимал «Сохранить», содержимое не менялось. Сообщений об ошибках также не отображается.
- Я удалил текстовый файл и снова запустил приложение. Это сработало.
Я не мог понять, в чем причина, поскольку сообщения об ошибке не показывалось. Любое понимание было бы здорово. Спасибо.
private Task WriteMessageToFile()
{
try
{
string folderPath = @"C:\ProgramData\Service";
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:\ProgramData\Service";
// 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 FileChanged;
public void CreateFileWatcher()
{
watcher = new FileSystemWatcher(@"C:\ProgramData\DPMService", "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);
}
}
Подробнее здесь: https://stackoverflow.com/questions/785 ... eadalltext
Мобильная версия