我需要在内存映射文件中找到某些元素。我已经设法映射了文件,但是在查找元素时遇到了一些问题。我的想法是将所有文件元素保存到一个列表中,然后在该列表中搜索。
如何创建一个返回包含映射文件所有元素的列表的函数?
// 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/