search
HomeBackend DevelopmentC#.Net TutorialC# program to get all files present in directory

C# 程序获取目录中存在的所有文件

Introduction

On the computer, we can store files in a directory, also known as a folder. A directory also contains shortcuts to other directories and files. If we want to know what all files have stored in a directory then C# also offers an easy way to do so. In this article, we will be learning a C# program to get all files present in a directory.

There are more than a couple of ways to know the files available in the directory. Let us discuss them in the upcoming sections.

1. GetFiles() method

In order to know the names of files that exist in the specified directory, we use the GetFiles() method.

public static string[] GetFiles (string path); 

We can use GetFiles() and GetDirectories() to know the files and subdirectories in the specified directory.

The parameter, the absolute or relative path of the directory, is a string. And it is case insensitive. This function returns an array containing a list of file names and their paths in the specified directory. When the directory is empty, an empty array is also returned.

algorithm

Now, let us discuss the algorithm for getting all files in a directory using the GetFiles() method.

Step 1 - First, we declare a string to store the address of the directory.

Step 2 We get the list of the files by using GetFiles() and store it in an array named fyles.

Step 3 Finally, we print the list of files.

Example

using System;
using System.IO;
public class Example {
   public static void Main() {
      string directloc = @"D:\mypc\addre";

      // files list from the root directory and prints it
      string[] fyles = Directory.GetFiles(directloc);
      Console.WriteLine(String.Join(Environment.NewLine, fyles));
   }
}

Output

abrew.txt
zuma.txt

Now, to get the details of the types of files that are present in the root directory i.e., the directory we are searching and its subfolders then we use the '*' pattern and SearchOption.AllDirectories which retrieve the multiple types of files available in the directory and its subdirectories.

Algorithm for SearchOption.AllDirectories

Now, let’s discuss the algorithm to get all the files present in a directory and its subdirectories using SearchOption.AllDirectories method.

Step 1 First, we declare a string to store the address of the directory.

Step 2 We get the list of the files in the directory and its subdirectories by using SearchOption.AllDirectories and store it in an array named fyles.

Step 3 Finally, we print the list of files.

Example

using System;
using System.IO;

public class Example {
   public static void Main() {
      string directloc = @"D:\mypc\addre";

      // files list from the root directory and its subdirectories and prints it
      string[] fyles = Directory.GetFiles(directloc, "*", SearchOption.AllDirectories);
      Console.WriteLine(String.Join(Environment.NewLine, fyles));

   }
} 

Output

abrew.txt
zuma.txt

So, by using the GetFiles() method, we can know the files in the directory and its subdirectories. Now, we move to the next section and discuss the EnumerateFiles method to understand the files in a directory and its subdirectories.

2. EnumerateFiles method

From the method's name, we can say that this is an enumerable collection returning method. So, this method returns an enumerable collection of complete file names in a given directory that matches the user-defined search and additionally explores folders.

public static System.Collections.Generic.IEnumerable EnumerateFiles (string path, string searchPattern, System.IO.SearchOption searchOption); 

Here, searchOption is a parameter that indicates whether the search should include only the current path or all subdirectories. searchPattern is a search string that matches file names in user-defined paths. It can contain valid literal paths and wildcard characters (* and ?), but regular expressions are not supported.

algorithm

Now, let’s discuss the algorithm to get all the files present in a directory using Directory.EnumerateFiles() method.

Step 1 First, we declare a string to store the address of the directory.

Step 2 We get the list of files in the directory and its subdirectories by using Directory.EnumerateFiles(directloc, "*", SearchOption.AllDirectories), and store it in a variable called fyles.

Step 3 Finally, we print the list of files.

Example

using System;
using System.IO;
using System.Collections.Generic;

public class Example {
   public static void Main() {
      string directloc = @"D:\mypc\addre";

      // files list from the root directory and its subdirectories and prints it
      var fyles = Directory.EnumerateFiles(directloc, "*", SearchOption.AllDirectories);
      Console.WriteLine(String.Join(Environment.NewLine, fyles)); 
   }
} 

输出

abrew.txt
zuma.txt

在这个方法中,searchPattern非常重要,因为它是通配符和字面字符的混合。它不允许使用正则表达式。以下是通配符和它们的匹配项。

的中文翻译为:

Wildcard Specifier

Matches

匹配

*(星号)

Zero or more characters in that position

?(question mark)

Exactly one character in that position

If we use '*o' then each file name is checked to end with o. And if we use 'a*' then each file name is checked to start with a. Also when the asterisk wildcard character is used in searchPattern and the name of a three-character file extension, such as "*.txt," this returns files with extensions that have with the stated extension. Now, let’s see another method.

3. Directory.GetFileSystemEntries() Method

This method returns the names of all files and subdirectories that meet the conditions given by the programmer. The syntax for this method is as follows.

public static string[] GetFileSystemEntries (string path); 

另一个选择是利用 Directory。GetFileSystemEntries() 方法检索提供路径中所有文件和子目录的名称。它可以使用搜索模式和搜索选项进行重载。当提供了搜索模式时,该方法将其与路径中的文件和文件夹名称进行比较。如果使用了 SearchOption.AllDirectories 选项,它将搜索所有子目录。

Algorithm

现在,让我们讨论使用 Directory.GetFileSystemEntries() 方法获取目录中所有文件的算法。

步骤 1  首先,我们声明一个字符串来存储目录的地址。

第二步 − 通过使用Directory.GetFileSystemEntries(rootdir, "*", SearchOption.AllDirectories)获取目录及其子目录中的文件列表,并将其存储在一个数组中。

Step 3  Finally, we print the list of files.

Example

using System;
using System.IO;

public class Example {
   public static void Main() {
      string directloc = @"D:\mypc\addre";
      
      // files list from the root directory and its subdirectories and prints it
      string[] fyles = Directory.GetFileSystemEntries(directloc, "*", SearchOption.AllDirectories);
      Console.WriteLine(String.Join(Environment.NewLine, fyles));
   }
} 

输出

abrew.txt
zuma.txt

Conclusion

所以,这篇文章就到这里了。在这篇文章中,我们学习了如何编写一个C#程序来获取目录中的所有文件。我们讨论了不同的方法来实现这个目标。我们还了解了这些方法的算法,并学习了它们的代码。希望这篇文章能够增加你对C#的知识。

The above is the detailed content of C# program to get all files present in directory. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools