© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
13 replies
bl4ck

Fastest way to read specific line from string

I'm working on a project that involves reading specific lines of a file multiple times. I'm afraid this ReadLine function is the reason it takes a painfully long time to finish so I'm trying to optimize it, but I'm not sure what is the fastest way to do it

This was my old code:
    //public static string ReadLine(string text, int lineNumber)
    //{
    //    var reader = new StringReader(text);
//
    //    string line;
    //    int currentLineNumber = 0;
//
    //    do
    //    {
    //        currentLineNumber += 1;
    //        line = reader.ReadLine();
    //    }
    //    while (line != null && currentLineNumber < lineNumber);
//
    //    return (currentLineNumber == lineNumber) ? line :
    //                                               string.Empty;
    //}
    //public static string ReadLine(string text, int lineNumber)
    //{
    //    var reader = new StringReader(text);
//
    //    string line;
    //    int currentLineNumber = 0;
//
    //    do
    //    {
    //        currentLineNumber += 1;
    //        line = reader.ReadLine();
    //    }
    //    while (line != null && currentLineNumber < lineNumber);
//
    //    return (currentLineNumber == lineNumber) ? line :
    //                                               string.Empty;
    //}


This is my new code: (prevText is in place in case it reads the same thing so that it skips splitting it)

    private string[] splitString = null;
    public static string prevText = "";
    public static string ReadLine(string text, int lineNumber)
    {

        if (!text.Equals(prevText)) Instance.splitString = text.Split('\n');
        
        prevText = text;
        return Instance.splitString[lineNumber - 1];
    }
    private string[] splitString = null;
    public static string prevText = "";
    public static string ReadLine(string text, int lineNumber)
    {

        if (!text.Equals(prevText)) Instance.splitString = text.Split('\n');
        
        prevText = text;
        return Instance.splitString[lineNumber - 1];
    }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Would it be the fastest way to read text from a website with HttpWebRequest?
C#CC# / help
4y ago
✅ String interpolation next line
C#CC# / help
2y ago
❔ How to convert line endings from my not encypted string to my encypted string
C#CC# / help
4y ago