4 File and network I/O

 

This chapter covers

  • Reading and writing files
  • Working with JSON
  • Making HTTP requests
  • Unblocking programs with asynchronous programming

Few things are more fundamental to developing applications than file I/O (input/output). A lot of file I/O happens behind the scenes. .NET applications, for example, are typically comprised of multiple DLL files, and the runtime handles when and how to load them. Configuration is often loaded from files. Applications may read text files and parse their contents into objects or transform them into other formats.

4.1 Reading and writing files

In this section, we’ll explore how to explicitly locate, read, and write files in code using .NET’s built-in libraries. Most of these APIs are available in the System.IO namespace, which is automatically included with implicit using statements.

4.1.1 Building a custom template

In this chapter, you’ll create a lot of console applications with some boilerplate code that we used in previous chapters. We’ll save a lot of time if we create a custom dotnet new template with the code to handle command-line arguments. Let’s start by creating a new console application, using the commands from the following listing.

Listing 4.1 Terminal commands to create a new console application
dotnet new console --name CmdArgsTemplate
cd CmdArgsTemplate
dotnet add package CommandLineParser     #1

4.1.2 Finding files in folders

4.1.3 Finding text in a file

4.1.4 Disposing the StreamReader with using

4.1.5 Parsing command-line arguments

4.2 Working with JSON

4.2.1 Reading JSON documents

4.2.2 Writing JSON documents

4.2.3 JSON serialization

4.3 Making HTTP requests