Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

ssis

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;

}


    } 
like image 815
James Khan Avatar asked Dec 01 '22 06:12

James Khan


1 Answers

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
}
like image 190
Tigran Avatar answered Dec 05 '22 16:12

Tigran