C# - 返回字符串文件中有多少行 [英] C# - return how many lines there are in a string file

查看:694
本文介绍了C# - 返回字符串文件中有多少行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我一直在努力解决这个简单的问题:给出一条文字,每行用新行字符分隔,返回有多少行。



我的代码如下。



亲切的问候



我的尝试:



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();
    }
}

推荐答案

哦,有很多方法!

计算字符串中的行数 [ ^ ] - 读一读,它会向您展示多种方式......以及它们在性能方面的成本。
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.


根据您的说法,我认为问题是:您的文件路径名称错误。一个不太可能的问题是你试图读取一个没有...或非常奇怪,或混合......行分隔符字符的文件。



注意:我没有考虑检测文件是否被锁定的问题,或者您被拒绝通过其权限设置访问该文件:我认为这些方面的运行时错误对您来说是显而易见的。



试试这个:
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(


文件扩展名{extension}无效);

if(File.Exists(filepath))
{
try
{
return File.ReadLines(filepath).Count();
}
catch(例外e)
{
Console.WriteLine(
"File extension {extension} is not valid"); if (File.Exists(filepath)) { try { return File.ReadLines(filepath).Count(); } catch (Exception e) { Console.WriteLine(


这篇关于C# - 返回字符串文件中有多少行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆