【问题标题】:Reading number of rows in a text file through SQL in C#通过C#中的SQL读取文本文件中的行数
【发布时间】:2015-09-11 03:54:43
【问题描述】:

我有一个流,我将其转换为字符串,然后写入 C: 上的文本文件(或 csv,并不重要)。现在我想访问该文件 (C:\InterfaceFiles\Requirements.txt) 并确定该文件中的行数。 SQL可以做到吗,还是我需要使用其他命令?

编辑:在 cmets 中使用 @Malte R 的解决方案。

string[] filearray = File.ReadAllLines("C:\\InterfaceFiles\\" + query);
count = filearray.Length;
Console.WriteLine(query + " row count = " + count);

【问题讨论】:

  • 你可以使用'File.ReadAllLines()',它返回一个数组,你可以检查它的长度。
  • SQL 可以做到这一点:参见 [此处][1]。 [1]:stackoverflow.com/a/12502435/4556142

标签: c# sql database localhost


【解决方案1】:

您可以使用 Microsoft 文本驱动程序通过 ADO.Net ODBC 提供程序连接到文本文件。见Connecting to a Text file using ADO.NET

也就是说,您最好使用 StreamReader 读取文件:

using System.IO;

int counter = 0;
string line;

// Read the file and display it line by line.
StreamReader file = new StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();

【讨论】:

    【解决方案2】:

    所以,您似乎对读取文件和处理异常有所了解(非常推荐),但这是我将使用的 while 循环

    while((line = file.ReadLine()) != null)
    {
       counter++;
    }
    

    【讨论】:

    • 查看我的评论,一个更简单的解决方案^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多