简体   繁体   中英

How to loop through all text files in a directory C#

This piece of code takes a row from 1.txt and splits it into columns. Now I have a directory of 200 + files with ending something.txt and I want them all to open one at a time and this process below run . What is the easiest way to loop thro all the files without changing my code too much ?

Snippet of code currently ;

    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;

}


    } 

You can simply use Directory.EnumerateFiles() to iterate over the files colection of the specified directory.

So you can insert your code inside foreach loop, like:

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

  //your code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM