我有两个WPF应用程序,当我想从一个应用程序写入文件并读取从另一个应用程序写入的数据时,我在两个应用程序中使用相同的文本文件。
但我不能这样做,因为这两个应用程序同时使用同一文件。
谁能帮我做一下。
我写这段代码,但什么也没做:
try
{
int nofiles = Directory.GetFiles("E:\\files", "*.txt").Length;
nofiles++;
StreamWriter write = new StreamWriter("E:\\files\\" + nofiles + ".txt");
write.WriteLine(itemId);
write.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
App.Current.Shutdown();
最佳答案
您可以在两个应用程序中使用Mutex使用进程间同步。确保尽快释放Mutex。您需要在所有访问文件的进程中提供以下类似的内容,以同步访问。
Mutex m = new Mutex(false, "MyMutex");
m.WaitOne();
//File read or writing code goes here.
m.ReleaseMutex();
命名的系统互斥锁在整个操作系统中都是可见的,并且
可用于同步流程的活动。您可以建立
一个Mutex对象,它通过使用
接受名称MSDN的构造函数。