我会尽力说明我的情况。
我正在使用 C# 开发一个软件,它允许多个用户同时编辑一个公共目录下的同一个文件,并查看其他人所做的更改。
因此,我使用 FileSystemWatcher 来监视文件中的更改(以更新其他人的更改)和文本框的 textchanged(以保存对文件的更改,以便其他人的屏幕也将被更新)。
如果我输入字符(两个事件都被触发一次),它就可以工作 如果我尝试删除任何形式的字符(退格、删除等)它就不起作用它不会删除任何字符,并且光标总是重置到位置 0。我使用 box.SelectionStart 移动光标,当我输入字符时它正在工作。
我放了一个计数器来检查,我发现当我尝试删除字符时,两个事件都被触发了两次。
我试图搜索,但我得到了不同的答案......
提前致谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;`enter code here`
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;
using System.Windows.Threading;
namespace SharedFileEditor
{
public partial class EditorView : Window
{
private EditorModel model;
private FileSystemWatcher watcher;
private string path;
private int count = 0;
private int count2 = 0;
public EditorView()
{
InitializeComponent();
model = new EditorModel();
this.DataContext = model;
}
private void OpenClicked(object sender, RoutedEventArgs e)
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Filter = "Text files (*.txt)|*.txt";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
watcher = new FileSystemWatcher(System.IO.Path.GetDirectoryName(dialog.FileName), "*.txt");
Console.WriteLine(System.IO.Path.GetDirectoryName(dialog.FileName));
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEve`enter code here`nts = true;
path = dialog.FileName;
HandleOpen(dialog.FileName);
}
}
}
internal void HandleOpen(string path)
{
FileStream f = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader reader = new StreamReader(f);
model.Content = reader.ReadToEnd();
reader.Close();
}
private void OnChanged(object source, FileSystemEventArgs e)
{
if (this.Box.Dispatcher.CheckAccess())
{
try
{
FileStream f = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader reader = new StreamReader(f);
model.Content = reader.ReadToEnd();
this.Box.CaretIndex = model.Cursor;
reader.Close();
Console.WriteLine("read:" + count2++);
}
catch (IOException x)
{
Console.WriteLine(x.Message);
}
}
else
{
this.Box.Dispatcher.Invoke(
new updateContent(OnChanged), source, e);
}
}
private void ContentChanged(object sender, TextChangedEventArgs e)
{
FileStream f = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter writer = new StreamWriter(f);
writer.Write(this.Box.Text);
model.Cursor = this.Box.SelectionStart;
model.Content = this.Box.Text;
writer.Close();
Console.WriteLine("write:"+count++);
}
public delegate void updateContent(object source, FileSystemEventArgs e);
}
}