visualstudio2010-从C#中的内存映射文件中查找元素

本文关键字:文件 查找 元素 映射 visualstudio2010- 内存 | 更新日期: 2023-09-27 17:58:37

我需要在内存映射文件中找到某些元素。我已经设法映射了文件,但是在查找元素时遇到了一些问题。我的想法是将所有文件元素保存到一个列表中,然后在该列表中进行搜索。

如何创建一个函数来返回一个包含映射文件所有元素的列表?

// Index indicates the line to read from
public List<string> GetElement(int index) {
}

我映射文件的方式:

    public void MapFile(string path)
    {
        string mapName = Path.GetFileName(path);
        try
        {
            // Opening existing mmf
             if (mapName != null)
             {
                 _mmf = MemoryMappedFile.OpenExisting(mapName);
             }
             // Setting the pointer at the start of the file
             _pointer = 0;
             // We create the accessor to read the file
             _accessor = _mmf.CreateViewAccessor();
             // We mark the file as open
             _open = true;
        }
        catch (Exception ex) {....}
        try
        {
            // Trying to create the mmf
            _mmf = MemoryMappedFile.CreateFromFile(path);
            // Setting the pointer at the start of the file
             _pointer = 0;
            // We create the accessor to read the file
            _accessor = _mmf.CreateViewAccessor();
            // We mark the file as open
            _open = true;
        }
        catch (Exception exInner){..}
    }

我正在映射的文件是一个UTF-8 ASCII文件。没什么奇怪的。

我所做的:

    var list = new List<string>();
    // String to store what we read
    string trace = string.Empty;
    // We read the byte of the pointer
    b = _accessor.ReadByte(_pointer);
    int tracei = 0;
    var traceb = new byte[2048];
    // If b is different from 0 we have some data to read
    if (b != 0)
    {
        while (b != 0)
        {
            // Check if it's an endline
            if (b == ''n')
            {
                trace = Encoding.UTF8.GetString(traceb, 0, tracei - 1);
                list.Add(trace);
                trace = string.Empty;
                tracei = 0;
                _lastIndex++;
            }
            else
            {
                traceb[tracei++] = b;
            }
            // Advance and read
            b = _accessor.ReadByte(++_pointer);
        }
    }

该代码对人类来说很难阅读,而且效率也不高。我该如何改进?

visualstudio2010-从C#中的内存映射文件中查找元素

您正在重新发明StreamReader,它正是您所做的。您真的想要一个内存映射文件的几率很低,它们占用了大量的虚拟内存,只有在以不同的偏移量重复读取同一文件时,才能获得回报。这是非常不可能的,文本文件必须按顺序读取,因为你不知道行有多长。

这使得这一行代码可能是您发布内容的最佳替代品:

string[] trace = System.IO.File.ReadAllLines(path);