[英]How to loop through all text files in a directory C#
這段代碼從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;
}
}
您可以簡單地使用Directory.EnumerateFiles()遍歷指定目錄的文件集合。
因此,您可以將代碼插入foreach循環內,例如:
foreach (var file in
Directory.EnumerateFiles(@"C:\\P\\DataSource2_W\\TextFiles\\Batch1", "*.txt"))
{
//your code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.