我在搜索文件内容时遇到性能问题。我正在使用FileStream
类来读取文件(每个搜索将涉及大约10个文件,每个文件大小约为70 MB)。但是,在我的搜索过程中,所有这些文件都将被另一个进程同时访问和更新。因此,我不能使用Buffersize
来读取文件。尽管我使用的是正则表达式,但在StreamReader
中使用缓冲区大小需要3分钟。如何使用FileSteam加速读取文件
有没有人遇到类似的情况,并可以提供任何提高文件搜索性能的指针?
代码段
private static int BufferSize = 32768;
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (TextReader txtReader = new StreamReader(fs, Encoding.UTF8, true, BufferSize))
{
System.Text.RegularExpressions.Regex patternMatching = new System.Text.RegularExpressions.Regex(@"(?=\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})(.*?)(?=\n\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex dateStringMatch = new Regex(@"^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}");
char[] temp = new char[1048576];
while (txtReader.ReadBlock(temp, 0, 1048576) > 0)
{
StringBuilder parseString = new StringBuilder();
parseString.Append(temp);
if (temp[1023].ToString() != Environment.NewLine)
{
parseString.Append(txtReader.ReadLine());
while (txtReader.Peek() > 0 && !(txtReader.Peek() >= 48 && txtReader.Peek() <= 57))
{
parseString.Append(txtReader.ReadLine());
}
}
if (parseString.Length > 0)
{
string[] allRecords = patternMatching.Split(parseString.ToString());
foreach (var item in allRecords)
{
var contentString = item.Trim();
if (!string.IsNullOrWhiteSpace(contentString))
{
var matches = dateStringMatch.Matches(contentString);
if (matches.Count > 0)
{
var rowDatetime = DateTime.MinValue;
if (DateTime.TryParse(matches[0].Value, out rowDatetime))
{
if (rowDatetime >= startDate && rowDatetime < endDate)
{
if (contentString.ToLowerInvariant().Contains(searchText))
{
var result = new SearchResult
{
LogFileType = logFileType,
Message = string.Format(messageTemplateNew, item),
Timestamp = rowDatetime,
ComponentName = componentName,
FileName = filePath,
ServerName = serverName
};
searchResults.Add(result);
}
}
}
}
}
}
}
}
}
}
return searchResults;
你看过http://stackoverflow.com/questions/14827350/faster-way-of-searching-a-string-in-text-files –
你说多个文件正在被多个进程访问和更新,你怎么解决你的并发问题? –
嗨Yacoub,我目前的搜索不打扰任何未来的更新文件。我所需要的是我需要打开该文件并用字符串进行搜索,目前可用。 – Uma