【问题标题】:How to loop through all text files in a directory C#如何遍历目录C#中的所有文本文件
【发布时间】:2012-05-16 09:54:28
【问题描述】:

这段代码从 1.txt 中取出一行并将其拆分为列。现在我有一个包含 200 多个文件的目录,结尾为 something.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# .net ssis


    【解决方案1】:

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

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

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

    【讨论】:

    • 由于微软的错误,不得不把它改成这个。 foreach (目录中的var文件.GetFiles(@"C:\\P\\DataSource2_W\\TextFiles\\Batch1\\", "*.txt")) {
    • 感谢您的回复。非常感谢。
    • 既然已经有@,为什么还要有\\?
    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2016-08-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多