Search code examples
c#.netshared-memorymemory-mapped-files

Sharing variable using MemoryMappedFile gives error


I need to share a variable value from App "A" to different applications on same system. I need to use only MemoryMappedFiles as per requirement. I created another simple App "B" which reads value of shared variable from App A. But App "B" gives error

Unable to find the specified file.

Sample App A and B written in C# using VS 2012 :

On Button click event of app A to share 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;
}

On Button click event of app B to read 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 the shared variable from App B it gives error

Unable to find the specified file

Do i need to write variable value in txt file and then share it ?


Solution

  • Memory mapped files are two types

    • Persisted memory mapped file
    • Non persisted memory mapped file

    You're creating Non persisted memory mapped file, so when the last process to close then handle of the MMF, it will be destroyed. You're closing the handle by calling Dispose on it through using statement, and thus MMF is destroyed.

    You either need to keep the MMF open, or use Persisted memory mapped file. To keep the MMF open, just don't dispose it.

    For more information