
QR codes are a simple and very popular way of exchanging data and information - even in .NET. They have become part of everyday life.
Unfortunately, .NET does not natively support the generation of QRCodes; we have to rely on the community. Fortunately, there is a very good library that we can use: QRCoder by Raffael Herrmann .
Install QRCoder
The installation is simple. We can install the library via NuGet:
1dotnet add package QRCoder
Using QRCoder
The structure and use of the library is very simple: we basically just need to create an instance of the QRCodeGenerator class and call the CreateQrCode method. The CreateQrCode method returns a QRCodeData object, which we can then convert into a Bitmap object.
A more realistic example is that we abstract the generation of the QRCode into a provider, which allows us to separate the implementation from the use and also to implement unit tests more easily.
1// Defining the QRCodeProvider class
2// Add an interface to your code!
3public class QRCodeProvider
4{
5 // Creating a new instance of QRCodeGenerator
6 // In principle, this class supports IDisposable, but we can re-use this instance
7 private static readonly QRCodeGenerator s_qrGenerator = new();
8
9 // Method to generate the QR code
10 public byte[] GeneratePng(string text)
11 {
12 // Creating the QR code data with our defaults
13 using QRCodeData qrCodeData = s_qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
14
15 // Creating a new instance of PngByteQRCode with the QR code data
16 // We can also use other Image types, like BitmapByteQRCode
17 PngByteQRCode qrCode = new (qrCodeData);
18
19 // Returning the QR code as a graphic
20 return qrCode.GetGraphic(pixelsPerModule: 20);
21 }
22}
The QRCodeProvider class can now either be used directly or integrated cleanly into a dependency injection container with an additional interface.
By calling the provider, we can generate our QRCode as a PNG with a handful of code - in this example stored on the file system.
1// NuGet: https://github.com/codebude/QRCoder
2using QRCoder;
3
4namespace BenjaminAbt_Samples_QrCode // Defining the namespace
5{
6 internal class Program // Defining the Program class
7 {
8 static void Main(string[] args)
9 {
10 // Creating a new instance of QRCodeProvider
11 // This is our own abstraction
12 QRCodeProvider qrCodeProvider = new();
13
14 // Defining the path where the QR code will be saved
15 // You can use different types of images and also svg or In-Memory
16 string path = @"C:\temp\qrcodetest.png";
17
18 string sampleText = "Hello World";
19
20 // Generating the QR code
21 byte[] png = qrCodeProvider.GeneratePng(sampleText);
22
23 File.WriteAllBytes(path, png); // Writing the QR code to the file
24 }
25 }
26
27 // QRCodeProvider here
28}

Comments