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
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
[
^]