Exercise - Work with the file system
You can use .NET to find and return information about files and folders.
Tailwind Traders has many physical stores all over the world. Every night, each store creates a file named sales.json that contains the total of all sales for that day. These files are organized in folders named with the store ID.
Note
This module uses the .NET CLI (Command Line Interface) and Visual Studio Code for local development. After completing this module, you can apply the concepts you've learned by using a development environment like Visual Studio (Windows) or Visual Studio for Mac (macOS), or continue development in Visual Studio Code (Windows, Linux, & macOS).
This module uses the .NET 8.0 SDK. Ensure that you have .NET 8.0 installed by running the following command in your preferred command terminal:
dotnet --list-sdks
Output similar to the following example appears:
6.0.317 [C:\Program Files\dotnet\sdk]
7.0.401 [C:\Program Files\dotnet\sdk]
8.0.100 [C:\Program Files\dotnet\sdk]
Ensure that a version that starts with 8
is listed. If none is listed or the command isn't found, install the most recent .NET 8.0 SDK.
Clone the project
In this exercise, you write a .NET program that searches a directory and its subdirectories for files named sales.json.
A starter project has already been created for you. You clone it using the integrated terminal in Visual Studio Code.
Open Visual Studio Code.
In the main menu, select View > Terminal to open a terminal window.
(Optional) In the terminal window, change to a directory to which you want to copy the files, such as
c:\MyProjects
.In the terminal window, run the following command to clone the starter project and go to the cloned project:
git clone https://github.com/MicrosoftDocs/mslearn-dotnet-files && cd mslearn-dotnet-files
Run the following command to create a new .NET Console project:
dotnet new console -f net8.0 -n mslearn-dotnet-files -o .
Run the following command to open the new .NET project in the same instance of Visual Studio Code:
code -a .
Tip
At this point, Visual Studio Code might prompt you that required assets to build and run the project are missing.
Select the triangle with the exclamation point and then select Relaunch terminal to add the files that allow Visual Studio Code to run and debug the project.
In the Explorer window, under mslearn-dotnet-files, expand the stores folder and each of the numbered folders inside.
Find the sales.json files
The following tasks create a program to find all the sales.json files in all folders of the mslearn-dotnet-files
project.
Include the System.IO namespace
In the Explorer window, select the
Program.cs
file to open it in the editor.Paste the following code into the first line of the
Program.cs
file to import theSystem.IO
andSystem.Collections.Generic
namespaces:using System.IO; using System.Collections.Generic;
Note
Starting with .NET 6, the two statements in the preceding code are automatically included in a new project by way of the ImplcitUsings
property group. Because we specified the -f net8.0
flag when we created a new console project, they are implicitly added. However, if you're working with an older project, they need to be included in the Program.cs
file, and it doesn't affect this project if you leave them in the file.
Write a function to find the sales.json files
Create a new function called FindFiles
that takes a folderName
parameter.
Replace the Console.WriteLine("Hello, World!"); line with the following code:
IEnumerable<string> FindFiles(string folderName) { List<string> salesFiles = new List<string>(); var foundFiles = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories); foreach (var file in foundFiles) { // The file name will contain the full path, so only check the end of it if (file.EndsWith("sales.json")) { salesFiles.Add(file); } } return salesFiles; }
Insert the following code below the
using
statements to call theFindFiles
function. This code passes in the stores folder name as the location to search for files.var salesFiles = FindFiles("stores"); foreach (var file in salesFiles) { Console.WriteLine(file); }
Press Ctrl+S (or Cmd+S macOS) to save the
Program.cs
file.
Run the program
Enter the following command in the terminal window to run the program:
dotnet run
The program should show the following output:
stores/sales.json stores/201/sales.json stores/202/sales.json stores/203/sales.json stores/204/sales.json
Excellent! You've successfully written a command-line program that traverses all folders in the stores
directory and lists all the sales.json files that were found.
In this example, the path to the stores directory was rather simple, and in the working directory of the program. In the next unit, you'll learn how to construct complex structures that work across operating systems by using the Path
class.
Got stuck?
If you had any problems running the program, here's the completed code for the Program.cs
file. Replace the contents of your Program.cs
file with this code:
var salesFiles = FindFiles("stores");
foreach (var file in salesFiles)
{
Console.WriteLine(file);
}
IEnumerable<string> FindFiles(string folderName)
{
List<string> salesFiles = new List<string>();
var foundFiles = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
foreach (var file in foundFiles)
{
// The file name will contain the full path, so only check the end of it
if (file.EndsWith("sales.json"))
{
salesFiles.Add(file);
}
}
return salesFiles;
}