开发者

Reading specific part of a File Content

How to read a string in another string where between Starting Index and first-encountered Ending Index

I have one giant file which contains info for each customers and they seperated the customers info with Starting and Ending Indexes and I need to get a specific customer info to display.

    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)

Nothing much tho. But it reads the file and put that giant file into sFileContent variable. I am not sure how efficient this way is (seems worse than MemoryStream).

Index strings can be more than 1 character.

Edit:

More info about the file, the file contains only one giant line and that lines contains all the info. I cannot touch on that file exc开发者_运维技巧ept for reading it since it has really confidential data.

I am looking for the string between Starting Index and First-encountered Ending Index exclusively.


You should read the file line-by-line:

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

This way, you'll never have more than one line in memory at a time.


DONT READ THE WHOLE LINE

Create a Binary / Text reader and call the read method with the start and end index. If the file is huge then optimise with a binary reader or something like that.

From -- 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);
            }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜