Returns the raw number of the current line count. : Text File Read Write « File Stream « C# / C Sharp






Returns the raw number of the current line count.

        
using System;
using System.Diagnostics.Contracts;


public class TextUtilities
{
    public static int GetLineCount(String text)
    {
        int lcnt = 1;
        for (int i = 0; i < text.Length; i++)
        {
            if (text[i] == '\n')
                lcnt += 1;
        }
        return lcnt;
    }

    public static int GetFirstCharIndexFromLineIndex(string text, int lineIndex)
    {
        if (text == null)
            throw new ArgumentNullException("text");
        if (lineIndex <= 0)
            return 0;

        int currentLineIndex = 0;
        for (int i = 0; i < text.Length - 1; i++)
        {
            if (text[i] == '\n')
            {
                currentLineIndex += 1;
                if (currentLineIndex == lineIndex)
                    return Math.Min(i + 1, text.Length - 1);
            }
        }

        return Math.Max(text.Length - 1, 0);
    }
    public static int GetLastCharIndexFromLineIndex(string text, int lineIndex)
    {
        if (text == null)
            throw new ArgumentNullException("text");
        if (lineIndex < 0)
            return 0;

        int currentLineIndex = 0;
        for (int i = 0; i < text.Length - 1; i++)
        {
            if (text[i] == '\n')
            {
                if (currentLineIndex == lineIndex)
                    return i;
                currentLineIndex += 1;
            }
        }

        return Math.Max(text.Length - 1, 0);
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Read and Write a Text File
2.Read text file line by line
3.Read ASCII string from byte bufferRead ASCII string from byte buffer
4.Reads and displays bytes until end-of-fileReads and displays bytes until end-of-file
5.Write string to a text file
6.Read whole text file to the end
7.Read text file line by line with exception catch
8.Text file Write with format and write boolean value to a text file
9.Action Text Reader Line
10.Open and Append to a Log File
11.Read and Write to a Newly Created Data File
12.Read Text from a File
13.Read text file with File.OpenText
14.Write Text to a File
15.Read a text file and obtain it's contents.
16.Reads text from a file.
17.Saves the text to a file.
18.Read Text File From Ressource
19.Create a large file of 100 lines to upload
20.Creates or opens a file for writing and writes text to it.
21.Returns the zero-based line number where source appears in target.
22.Returns the number of lines appearing in target where a line is counted as a '\n'