共享内存,写入文件

时间:2011-08-22 21:27:23

标签: c# file memory save shared

我在碎片记忆中有TXT文件。 代码结束了。我一直试图将它从内存中取出并写入C:\驱动器中的文件。

但是我收到了一个错误:

    Type 'SharedMemSaveToFile.SharedMemSaver+Data' cannot be marshaled as an 
unmanaged structure; no meaningful size or offset can be computed.

如果我更改代码以将内存写入CMD,它可以工作,所以我知道内存在那里。我也试过用这些来写TXT:

 System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\file.txt");
 file.WriteLine(d);

using (StreamWriter outfile = new StreamWriter(d + @"C:\\file.txt"))
{
     outfile.Write(sb.ToString());
}

StreamWriter sw = new StreamWriter("file.txt");
    sw.Write(d);
    sw.Close();

谢谢!

    public class Data
    {
        static void Main(string[] args)
        {
            SharedMemSaver sf = new SharedMemSaver();
            sf.OpenView();
            String d = sf.GetData();
            System.IO.File.WriteAllText(@"C:\file.txt", d);

        }
    }

    #region Win32 API stuff
    public const int FILE_MAP_READ = 0x0004;

    [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern IntPtr OpenFileMapping(int dwDesiredAccess,
        bool bInheritHandle, StringBuilder lpName);

    [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern IntPtr MapViewOfFile(IntPtr hFileMapping,
        int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow,
        int dwNumberOfBytesToMap);

    [DllImport("Kernel32.dll")]
    internal static extern bool UnmapViewOfFile(IntPtr map);

    [DllImport("kernel32.dll")]
    internal static extern bool CloseHandle(IntPtr hObject);
    #endregion

    private bool fileOpen = false;
    private IntPtr map;
    private IntPtr handle;

    ~SharedMemSaver()
    {
        CloseView();
    }

    public bool OpenView()
    {
        if (!fileOpen)
        {
            StringBuilder sharedMemFile = new StringBuilder("Mem_Values");
            handle = OpenFileMapping(FILE_MAP_READ, false, sharedMemFile);
            if (handle == IntPtr.Zero)
            {
                throw new Exception("Unable to open file mapping.");
            }
            map = MapViewOfFile(handle, FILE_MAP_READ, 0, 0, Marshal.SizeOf((Type)typeof(Data)));
            if (map == IntPtr.Zero)
            {
                throw new Exception("Unable to read shared memory.");
            }
            fileOpen = true;
        }
        return fileOpen;
    }

    public void CloseView()
    {
        if (fileOpen)
        {
            UnmapViewOfFile(map);
            CloseHandle(handle);
        }
    }

    public String GetData()
    {
        if (fileOpen)
        {
            String data = (String)Marshal.PtrToStringAuto(map);
            return data;
        }
        else
        {
            return null;
        }
    }
}

}

2 个答案:

答案 0 :(得分:4)

我强烈建议使用内置的MemoryMappedFile类(.NET 4中的新增类)。

答案 1 :(得分:1)

请参阅Yahia对解决方案的回答。

但是尝试修复您的代码,错误消息显示全部:
你想用Marshal.SizeOf((Type)typeof(Data))得到什么? 它没有大小,因为它不包含数据。 查看 MSDN doc。 MapViewOfFile的最后一个参数"If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping."