Question

I have two WPF application i use the same text file in two applications when i want file to write from one application and read the data written from another application . but i can't do it because the two applications use the same file at same time . can any one help my to do it please . i write this code but don't make any thing :

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();
Était-ce utile?

La solution

You can use inter process synchronization using Mutex in both applications. Make sure you release Mutex as soon as possible. You need some thing like given below in all the processes accessing file to synchronize access.

Mutex m = new Mutex(false, "MyMutex");
m.WaitOne();
//File read or writing code goes here.   
m.ReleaseMutex(); 

Named system mutexes are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create a Mutex object that represents a named system mutex by using a constructor that accepts a name, MSDN.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top