VB.Net/C# function to read a specific line from a file


Here is a function to read a specific line from a file. Since lines in a file are generally variable length we can't use a seek index and instead will read through the file line by line looking for the one we want. That being the case you would only want to use this in instances where you will be reading just a specific line or two from a file. If you need to access more of the lines at once you may want to read the lines of the file into a string array using File.ReadAllLines().

VB.Net

''' <summary>
''' Reads a specified line from a text file.  Each call to this opens and loops until the specific line is found (since lines are variable length an index cannot be used).
''' </summary>
''' <param name="filePath"></param>
''' <param name="lineNumber"></param>
''' <returns></returns>
''' <remarks>This should be used in cases when a specific line is needed but you want to disregard the rest of the file (e.g. don't use this to loop through a file as it opens
''' and finds the specific line going through all previous lines).</remarks>
Public Shared Function ReadSpecificLine(filePath As String, lineNumber As Integer) As String
    Using sr As New StreamReader(filePath)
        ' Skip these lines
        For i As Integer = 1 To lineNumber - 1
            If sr.ReadLine() Is Nothing Then
                sr.Close()
                Throw New ArgumentOutOfRangeException(String.Format("The line number {0} is out of range.", lineNumber))
            End If
        Next

        ' This is the line we want, if it exists return it, otherwise throw an exception.
        Dim line As String = sr.ReadLine()

        If line Is Nothing Then
            Throw New ArgumentOutOfRangeException(String.Format("The line number {0} is out of range.", lineNumber))
        End If

        sr.Close()
        Return line
    End Using
End Function

C#

/// <summary>
/// Reads a specified line from a text file.  Each call to this opens and loops until the specific line is found (since lines are variable length an index cannot be used).
/// </summary>
/// <param name="filePath"></param>
/// <param name="lineNumber"></param>
/// <returns></returns>
/// <remarks>This should be used in cases when a specific line is needed but you want to disregard the rest of the file (e.g. don't use this to loop through a file as it opens
/// and finds the specific line going through all previous lines).</remarks>
public static string ReadSpecificLine(string filePath, int lineNumber)
{
    using (StreamReader sr = new StreamReader(filePath))
    {
        // Skip these lines
        for (int i = 1; i <= lineNumber - 1; i++)
        {
            if (sr.ReadLine() == null) {
                sr.Close();
                throw new ArgumentOutOfRangeException(string.Format("The line number {0} is out of range.", lineNumber));
            }
        }

        // This is the line we want, if it exists return it, otherwise throw an exception.
        string line = sr.ReadLine();

        if (line == null)
        {
            throw new ArgumentOutOfRangeException(string.Format("The line number {0} is out of range.", lineNumber));
        }
        
        sr.Close();
        return line;
    }
}

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.