Swapping variable with MemoryMappedFile gives error
I need to split the value of a variable from application "A" to different applications on the same system. I only need to use MemoryMappedFiles as per requirement. I created another simple application "B" that reads the value of a shared variable from application A. But application "B" gives an error
The specified file could not be found.
Sample Applications A and B written in C # using VS 2012:
In case of pressing the button in Appendix A to exchange the variable Name:
private void button1_Click(object sender, EventArgs e)
{
string Name = txtName.Text.ToString();
int howManyBytes = Name.Length * sizeof(Char) + 4;
label1.Text = howManyBytes.ToString();
using (var MyText = MemoryMappedFile.CreateOrOpen("MyGlobalData", howManyBytes, MemoryMappedFileAccess.ReadWrite))
{
byte[] array1 = new byte[howManyBytes];
array1 = GetBytes(Name);
using (var accessor = MyText.CreateViewAccessor(0, array1.Length))
{
accessor.WriteArray(0, array1, 0, array1.Length);
}
}
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
In the case of a mouse click in Application B to read the shared variable MyGlobalData:
try
{
using (var mmf = MemoryMappedFile.OpenExisting("MyGlobalData"))
{
using (var accessor = mmf.CreateViewAccessor(0, 34))
{
byte[] array1 = new byte[34];
accessor.ReadArray(0, array1, 0, array1.Length);
string result = System.Text.Encoding.UTF8.GetString(array1);
txtName.Text = result;
}
}
}
catch (Exception ex)
{
MessageBox.Show(" Error :- " + ex.Message.ToString());
}
When trying to read a shared variable from app B it gives an error
The specified file cannot be found
I need to write the value of a variable to a txt file and then share it?
source to share
Memory mapped files are of two types
- Saved memory file
- Immutable memory file
You are creating a persistently stored memory file, so when the last process closes the MMF handle, it will be destroyed. You close the handle by calling Dispose
on it with a statement, and thus the MMF is destroyed.
You either need to leave the MMF open or use a saved memory file. To keep the MMF open, just don't delete it.
source to share