开发者

How can I make my C# code check each file in a directory? [duplicate]

开发者 https://www.devze.com 2023-03-27 06:56 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: how to read all files inside particular folder
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

how to read all files inside particular folder

I have the following code which I came up with:

string[] lines = System.IO.File.ReadAllLines(@"C:\Notes\Variables1.txt");
foreach (string line in lines开发者_JS百科)
{
   process(line);
}

string[] lines = System.IO.File.ReadAllLines(@"C:\Notes\test1.txt");
foreach (string line in lines)
{
   process(line);
}

Is there a simple and reliable way that I can modify the code so that it looks up all the .txt files in my Notes directory and then reads each one in turn. Some way I can code this up without having to specify each file in turn and something that won't crash if the file is empty.


string[] files = Directory.GetFiles(source, "*.txt");
foreach(string filename in files) 
{
   //go do something with the file
}


Use the DirectoryInfo class to get a listing of all files.

Is has an overloaded EnumerateFiles method, just for this.


You can get a collection of the files in any given directory using Directory.GetFiles(). Then just process them one by one like you were already doing.

string[] files = Directory.GetFiles(@"C:\Notes", "*.txt", SearchOption.TopDirectoryOnly);
foreach(string file in files)
{
    string[] lines = File.ReadAllLines(file);
    foreach (string line in lines)
    {
        process(line);
    }        
}

There's a lot more in the System.IO namespace.


Use System.IO.Directory.ReadFiles

For example:

string[] filePaths = Directory.GetFiles(@"c:\Notes\", "*.txt")

Then simply iterate through the file paths


You want:

Directory.GetFiles(path, "*.txt");

This will return an array of names so you can loop over each file in turn:

foreach (string file in Directory.GetFiles(path, "*.txt"))
{
    string[] lines = System.IO.File.ReadAllLines(file);
    foreach (string line in lines)
    {
        process(line);
    }
}


string[] files = Directory.GetFiles(directory);
foreach(string filename in files)
{
   if (Path.GetExtension(filename) != ".txt")
      continue;

   string[] lines = System.IO.File.ReadAllLines(filename);
   foreach (string line in lines)
   {
      process(line);
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消