阅读文件内容的特定部分

时间:2011-09-08 17:48:46

标签: c# .net regex vb.net

如何读取Starting Index与首次遇到的Ending Index之间的另一个字符串中的字符串

我有一个巨大的文件,其中包含每个客户的信息,他们将客户信息与开始和结束索引分开,我需要获取特定的客户信息才能显示。

    Dim oFile As New FileInfo(sFileName)
    Dim sFileContent As String = oFile.OpenText().ReadToEnd()
    Dim iStartIndex As Integer = sFileContent.IndexOf(roNotification.StartByte)
    Dim iEndIndex As Integer = sFileContent.IndexOf(roNotification.EndByte, iStartIndex)
    Dim sCustomerInfo As String = sFileContent.Substring(iStartIndex + roNotification.StartByte.Length - 1, iEndIndex)

没什么。但它会读取文件并将该巨型文件放入sFileContent变量中。我不确定这种方式有多高效(看起来比MemoryStream差)。

索引字符串可以超过1个字符。

修改

有关该文件的更多信息,该文件只包含一个巨行,并且该行包含所有信息。除了阅读之外,我无法触及该文件,因为它有真正的机密数据。

我正在寻找开始索引和首次遇到的结束索引之间的字符串。

2 个答案:

答案 0 :(得分:3)

您应该逐行阅读文件:

Using reader = file.OpenText()
    Dim line As String
    While True
        line = reader.ReadLine()
        If ReferenceEquals(Line, Nothing) Then Exit While

        'Parse the line and figure out what to do with it
    End While
End Using

这样,你一次在内存中永远不会有多行。

答案 1 :(得分:1)

不要读全线

创建二进制/文本阅读器并使用开始和结束索引调用read方法。如果文件很大,那么使用二进制阅读器或类似的东西进行优化。

从 - http://msdn.microsoft.com/en-us/library/9kstw824.aspx

 using (StreamReader sr = new StreamReader(path)) 
        {
            //This is an arbitrary size for this example.
            char[] c = null;

            while (sr.Peek() >= 0) 
            {
                c = new char[5];
                sr.Read(c, 0, c.Length);
                //The output will look odd, because
                //only five characters are read at a time.
                Console.WriteLine(c);
            }
 }
相关问题