c# - 在 C# 中从内存映射文件中查找元素

标签 c# visual-studio-2010 memory-management

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

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

// 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);
        }
    }

代码很难被人类阅读并且效率不高。我该如何改进它?

最佳答案

您正在重新发明 StreamReader,它的功能完全符合您的要求。您真的想要一个内存映射文件的可能性非常低,它们占用大量虚拟内存,只有当您以不同的偏移量重复读取同一个文件时,您才能获得返回。这是不太可能的,文本文件必须按顺序读取,因为您不知道行有多长。

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

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

关于c# - 在 C# 中从内存映射文件中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6263068/

相关文章:

c# - Visual Studio 2010 : How refer to a C# . 具有第三方依赖项的 Net 类库项目

c++ - 链表的链表的析构函数

ios - 在 UIWebView 中加载 NSURLRequest - 堆不断增长

c# - 社交对象 - 数据库结构、过滤、排序、可扩展性的最佳实践

c# - 添加 WiX 自定义操作以将 MSI 日志文件复制到 LOCALAPPDATA 文件夹

c - 作业 3.exe : 0xC0000005: Access violation reading location 0x33772c58 中 0x77ea15de 处出现未处理的异常

c# - VS2010 中的 FxCop 行为、代码分析和 SuppressMessage

objective-c - 为什么我的应用程序在迁移到 ARC 后充满了内存泄漏?

c# - 在 C++ 和 C# 之间编码类实例的指针

c++ - delete [] 在 Linux 中放置新对象失败