Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to loop through a folder of files in C#?

I trying to write a program that navigates the local file system using a config file containing relevant filepaths. My question is this: What are the best practices to use when performing file I/O (this will be from the desktop app to a server and back) and file system navigation in C#?

I know how to google, and I have found several solutions, but I would like to know which of the various functions is most robust and flexible. As well, if anyone has any tips regarding exception handling for C# file I/O that would also be very helpful.

like image 853
badpanda Avatar asked Jun 08 '10 14:06

badpanda


People also ask

Which loop can be used to iterate over files in a directory?

Using pathlib module With Python 3.4, you can also use the pathlib module. To iterate over files in a directory, use the Path. glob(pattern) function, which glob the given relative pattern in the specified directory and yield the matching files.

How do I loop a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).


1 Answers

You don't need a separate library, use the classes in the System.IO namespace like File, FileInfo, Directory, DirectoryInfo. A simple example:

var d = new DirectoryInfo(@"c:\");
foreach(FileInfo fi in d.GetFiles())
    Console.WriteLine(fi.Name);
like image 109
D'Arcy Rittich Avatar answered Sep 28 '22 05:09

D'Arcy Rittich