我正在尝试通过大小为 18033 行的大型 CSV 文件 (8MB) 搜索数据,这是在 .Net 版本 4 和 4.6.1 中尝试使用 Windows 窗体 (C#) 的桌面应用程序的要求。
我正在使用的函数的代码如下
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: 试图读取或写入受保护的内存。这通常表明其他内存已损坏。
在我使用 File.ReadAllLines 方法时也得到相同的异常。在两台不同的 PC 上,在 VS2017 和 VS 2019 中尝试过相同的代码。
关于错误的奇怪之处在于,如果在 while 循环中放置一个计数器,它会遍历 500 到 600 行,否则它会遍历整个文件并在过程结束时给我异常。即使我设置了 AccessViolationException,也不会命中。该代码在 Linqpad 中运行良好,因此我不确定 CSV 文件是否已损坏。
如果有人有任何想法会有所帮助。提前致谢。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句