C# – Serialize and deserialize a multidimensional array to JSON

System.Text.Json doesn’t support serializing / deserializing multidimensional arrays. When you try, it throws an exception like this – System.NotSupportedException: The type ‘System.Int[,] is not supported. You have three options: In this article, I’ll show an example of how to create a custom JsonConverter that handles multidimensional arrays. In this example, I’ll specifically show how to … Read more

ASP.NET Core – Client-side custom validation attributes

I wrote about how to add custom validation attributes. These are used for model validation on the server-side. You can also use these for client-side validation, which I’ll show in this article. 1 – Implement IClientModelValidator The first step is to implement the IClientModelValidator interface in the custom validation attribute class. This has a single … Read more

C# – JSON value could not be converted to System.String

When you send a request to ASP.NET with a JSON body, you get the following exception: System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1. You can’t deserialize JSON to a string. You’re either using a string parameter with [FromBody] or your model has a string … Read more

C# – Update records with Dapper

You can update records with Dapper by using Execute() with an UPDATE statement and passing in the parameters. Here’s an example: Dapper maps the properties from the param object to the query parameters (ex: it maps year to @year). You can pass in the parameters with an anonymous type (as shown above) or by passing … Read more

C# – Insert records with Dapper

You can insert records with Dapper by using Execute() on an INSERT statement and passing in a model object. Here’s an example of inserting a single movie record: Notice that you can simply pass in an object (param: movie) and Dapper handles the tedious parameter mapping for you. It tries to map properties from the … Read more

C# – Delete records with Dapper

You can delete records with Dapper by using Execute() with a DELETE statement and specifying the record ID as a parameter. Here’s an example: This deletes a single record from the Movies table. Delete multiple records When you’re deleting multiple records, you can efficiently execute a single DELETE statement with a WHERE clause including all … Read more

C# – Execute a stored procedure with Dapper

You can execute stored procedures with Dapper by specifying the name, parameters, and CommandType.StoredProcedure. Let’s say you have the following stored procedure (single parameter, returns movie rows): Here’s how to execute this stored procedure with Dapper and map its results to Movie objects: Use an output parameter To get a stored procedure’s output parameter, add … Read more

ASP.NET Core – Control the graceful shutdown time for background services

ASP.NET Core gives you a chance to gracefully shutdown your background services (such as cleaning up and/or finishing in-progress work). By default, you’re given a grand total of 5 seconds to shutdown all background services. If you need more time than this, there are a few ways to control the graceful shutdown time, which I’ll … Read more

C# – How to make a file read-only

There are two ways to programmatically make a file read-only: Here’s an example showing both ways to make a file read-only: Using File.SetAttributes() is useful when you want to manage all of file’s attributes at once. FileAttributes is an enum flag, so you can use bitwise operations to add/remove multiple attributes at once. That’s why … Read more

C# – How to set permissions for a directory (Windows only)

When you want to set permissions for a directory (and its files/subdirectories), you can use DirectoryInfo.GetAccessControl() to get the directory’s security, add/modify/remove access control rules, and then use DirectoryInfo.SetAccessControl() to apply the changes. Access control rules are a complex combination of different settings. They control being able to do things like creating a file in … Read more

C# – How to delete a directory

The simplest way to delete a directory is by using Directory.Delete() (in System.IO). Here are a few examples: You have to specify the path of the directory to delete. This can be an absolute or relative path. You can pass in a recursive flag, which tells it to delete everything in the directory (files and … Read more

C# – How to create directories

You can use Directory.CreateDirectory() to create a directory at the specified path (absolute or relative), like this: This creates the directory if it doesn’t exist, otherwise it does nothing. That means you don’t need to check if the directory exists before calling Directory.CreateDirectory(). In this article, I’ll go into more details about using Directory.CreateDirectory(). CreateDirectory() … Read more

C# – How to update a file’s contents

There are three ways to update a file’s content: Which option you pick depends on the file’s format and size. For example, if you’re writing to an existing CSV file, you’d append new lines to the end of the file. If you’re updating a JSON file, you’d read all the JSON content, make changes, then … Read more

C# – Search for files in a directory

Use Directory.EnumerateFiles() to search for files in a directory and then loop over the file paths (and then reading the files, or whatever you want to do with the info). Here’s an example of searching for files containing “hello” in the file name: Note: Use the wildcard character * to match anything. It returns an … Read more

C# – How to read a text file

The simplest way to read a text file is by using a high-level method in the .NET File API (in System.IO), such as File.ReadAllText(). These high-level methods abstract away the details of opening a file stream, reading it with StreamReader, and closing the file. Here’s an example of reading a text file’s content into a … Read more

C# – How to create a file and write to it

There are a few ways to create a file and write to it using the .NET File API (in System.IO). The simplest way is to use high-level methods like File.WriteAllText() and File.WriteAllLines(), specifying the file path and string(s) to write to the file. Here’s an example of using these (and their async equivalents): These high-level … Read more

C# – How to delete a file

You can use File.Delete() (in System.IO) to delete a file by specifying its relative or absolute path. Here’s an example: Note: Unlike other methods in the File API, there’s no async version of File.Delete(). If the specified file exists and the permissions are right, then File.Delete() deletes the file as expected. If there’s a problem, … Read more

ASP.NET Core – How to manually validate a model in a controller

Manually validating a model can mean a few different things. It depends on what you’re trying to do exactly. Are you trying to validate a model object against its validation attributes? Use TryValidateModel(). Are you trying to do validation logic manually (instead of using validation attributes)? You can add errors to ModelState in that case. … Read more