尝试读取或写入受保护的内存。这通常表明其他内存已损坏,同时使用 C# 读取 CSV 文件

Attempted to read or write protected memory. This is often an indication that other memory is corrupt, while reading CSV file using C#

我正在尝试通过一个大小为 18033 行的大型 CSV 文件 (8MB) 搜索数据,这是使用 Windows 表格 (C#) 在 .Net 版本 4 中尝试过的桌面应用程序的要求,并且4.6.1.

我使用的函数代码如下

private List<string> SearchData(string searchText)
    {
        try
        {
            List<string> dates = new List<string>();
            using (var csv = new FileStream(Config.DataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (BufferedStream bs = new BufferedStream(csv))
            using (StreamReader sr = new StreamReader(bs))
            {
                var lines = string.Empty;
                while ((lines = sr.ReadLine()) != null)
                {
                    if (lines.ToLower().Contains(searchText.ToLower()))
                    {
                        dates.Add(lines.Substring(0, 10));
                    }
                }
            }
            return dates;            
        }
        catch (Exception ex)
        {

            MessageBox.Show("Unable to search the file");
            ex.Data.Add("SearchText", searchText);
            Logger.Log(ex, "SearchData");
        }
        return null;
    }

但我收到以下异常

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

我在使用 File.ReadAllLines 方法时也遇到同样的异常。 在两台不同的 PC 上尝试了 VS2017 和 VS 2019 中的相同代码。

错误的奇怪之处在于,如果在 while 循环中放置一个计数器,它会遍历多达 500 到 600 行,否则它会遍历整个文件并在过程结束时给我异常。即使我设置了 AccessViolationException,也不会命中。 该代码在 Linqpad 中运行良好,因此我不确定 CSV 文件是否已损坏。

如果有人有任何想法会有所帮助。 提前致谢。

我建议您看一下 CsvHelper 库。据作者说,

Reading records will yield results so only one record is in memory at a time.

这可以避免您遇到的内存问题。