chapter four

4 File and Network IO

 

4.1 Reading and writing files

There are few things more fundamental to developing applications than file IO (Input/Output). A lot of file IO happens behind the scenes. For example, .NET applications are typically comprised of multiple DLL files and the runtime handles when and how to load them. 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 under the System.IO namespace, which is automatically included with implicit usings.

4.1.1 Building a custom template

In this chapter you’ll create a lot of console applications that have some boilerplate code that we’ve used in previous chapters. It will 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 4.1.

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

Note that the dotnet add package command will add the latest non-prerelease version of the package reference to the .csproj file. Open the CmdArgsTemplate.csproj file and add the global using for System.Console as shown in 4.2.

4.1.2 Finding files in folders

4.1.3 Finding text in a file

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

4.4 Unblocking programs with asynchronous programming

4.5 Summary