Click here to Skip to main content
15,890,336 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I've been struggling with what seems like such a simple question: "Given a text with each line separated by new line character, return how many lines there are.".

My code is below.

Kind regards

What I have tried:

    public static int CountLines(string text)
    {
        return File.ReadAllLines(text).Count();
    }
}
Posted
Updated 20-Jul-17 8:05am
Comments
Mehdi Gholam 20-Jul-17 4:38am    
... and what is your problem?
F-ES Sitecore 20-Jul-17 4:39am    
What's wrong with the code you have?
Member 13302374 20-Jul-17 4:41am    
It gives me an unhandled exception, stating "Illegal characters in path", when I build and run the code
Karthik_Mahalingam 20-Jul-17 6:36am    
what is the value in "text"
F-ES Sitecore 20-Jul-17 7:19am    
"text" is the name of a file and ReadAllLines returns the lines in that file. If "text" is the text where you want to count the lines of then you need to use Split as as suggested (though try splitting on "\r\n"). Or just google as suggested also, this is an incredibly trivial problem.

Oh, there are a load of ways!
Counting Lines in a String[^] - have a read, it'll show you many ways ... and how much they cost in performance terms.
 
Share this answer
 
Based on what you say, I think the problem is: you have a bad file path name. A much less likely problem is you are trying to read a file with no ... or very weird, or mixed-up ... line-separator character(s).

Note: I don't consider the issue of detecting whether the file is locked, or you are denied access to the file by its permission settings: I assume the run-time errors trheown by those aspects would be obvious to you.

Try this:
public static string[] validextensions = new[] {".txt",".cs", ".csv"};
        
public static int CountLines(string filepath)
{
    string extension = Path.GetExtension(filepath);
    
    if(! validextensions.Contains(extension)) throw new InvalidDataException($"File extension {extension} is not valid");
            
    if (File.Exists(filepath))
    {
        try
        {
            return File.ReadLines(filepath).Count();
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error reading file  {filepath} : {e.Message}");
        }
    }
    else
    {
        Console.WriteLine($"{filepath} : does not exist");
    }
    
    return -1;
}
But, you should consider if you really want to invoke reading the entire file only to count the lines: 'ReadLines returns an IEnumerable<string> : 'Count() will enumerate it. Assuming you are planning to use the text (lines) in the file, this makes more sense:
public static string[] validextensions = new[] {".txt",".cs", ".csv"};
        
public static int CountLines(string filepath, out string[] lines)
{
    string extension = Path.GetExtension(filepath);
    
    if(! validextensions.Contains(extension)) throw new InvalidDataException($"File extension {extension} is not valid");
            
    lines = null;
    
    if (File.Exists(filepath))
    {
        try
        {
            lines = File.ReadLines(filepath).ToArray();
            return lines.Length;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error reading file  {filepath} : {e.Message}");
        }
    }
    else
    {
        Console.WriteLine($"{filepath} : does not exist");
    }

    return -1;
}
Use example: ... in some method or EventHandler
C#
string[] readlines;
            
var nlines = CountLines(@"C:\Users\User\Desktop\Folder\file name.txt", out readlines);
There are many techniques available for reading files: an excellent article comparing them is: [^].

Keep in mind that while 'ReadLines is robust ... can deal with many types of line-endings ... there are many possibilities:
Quote:
Be aware that for unicode files, there are a number of different characters that are consider legal line-terminators. They include: Carriage return character (U+000D), Line feed character (U+000A), Carriage return character (U+000D) followed by line feed character (U+000A), Line separator character (U+2028), and the Paragraph separator character (U+2029). There is also sometimes a 'End of Text' (U+0003) character which may legally be used as the terminator of the last line of a file. – LBushkin J
[^]
 
Share this answer
 
v4
Hi, You could also try the below code.

C#
public static int CountLines(string text)
{
    return text.Split('\n').Length;
}
 
Share this answer
 
v3
Comments
Member 13302374 20-Jul-17 4:52am    
Hmm not working. I took out the split part and tried it again, as the given text is already separated by new line characters, but still it doesn't work
shikhar mittal 20-Jul-17 5:20am    
What is not working with the above solution? Also please post a sample string you are using for testing.
Afzaal Ahmad Zeeshan 20-Jul-17 10:40am    
I did not vote, and won't vote on this answer, just in case someone downvotes and you think I did it.

But, Shikhar, did you try "\r\n", on most cases that would be used to denote a new line. Perhaps, it would be much better if you use, Environment.NewLine to let .NET select new lines in your content.
Use the following code

string[] stringSeparators = new string[] {"\r\n"};

result = source.Split(stringSeparators, StringSplitOptions.None);

return result.Length
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900