如何循环遍历目录 C# 中的所有文本文件

本文关键字:文件 文本 何循环 循环 遍历 | 更新日期: 2023-09-27 18:34:23

这段代码从 1.txt 中获取一行并将其拆分为列。现在我有一个包含 200 + 个文件的目录,其中包含结束某些内容.txt我希望它们一次打开一个,下面的这个过程运行.在不对代码进行太多更改的情况下遍历所有文件的最简单方法是什么?

当前代码片段 ;

    string _nextLine;
    string[] _columns;
    char[] delimiters;

    delimiters = "|".ToCharArray();

    _nextLine = _reader.ReadLine();
    string[] lines = File.ReadAllLines("C:''P''DataSource2_W''TextFiles''Batch1''1.txt");

    //Start at index 2 - and keep looping until index Length - 2 
    for (int i = 3; i < lines.Length - 2; i++) 
    {     _columns = lines[i].Split('|');    
        // Check if number of cols is 3
    if (_columns.Length == 146)
    {
        JazzORBuffer.AddRow();
        JazzORBuffer.Server = _columns[0];
        JazzORBuffer.Country = _columns[1];
        JazzORBuffer.QuoteNumber = _columns[2];
        JazzORBuffer.DocumentName =_columns[3];
        JazzORBuffer.CompanyNameSoldTo=_columns[4];

    }   
         else
{
    // Debug or messagebox the line that fails
    MessageBox.Show("Cols:" + _columns.Length.ToString() + " Line: " + lines[i]);
    return;
}

    } 

如何循环遍历目录 C# 中的所有文本文件

您可以简单地使用 Directory.EnumerateFiles() 遍历指定目录的文件集合。

因此,您可以在 foreach 循环中插入代码,例如:

foreach (var file in 
  Directory.EnumerateFiles(@"C:''P''DataSource2_W''TextFiles''Batch1", "*.txt"))
{
  //your code
}