Comment générer des codes QR et des codes-barres en C#

Generate QR Codes in C# - Complete Tutorial for .NET Developers

This article was translated from English: Does it need improvement?
Translated
View the article in English

Need to generate QR codes in your C# application? This tutorial shows you exactly how to create, customize, and verify QR codes using IronBarcode—from simple one-line implementations to advanced features like logo embedding and binary data encoding.

Whether you're building inventory systems, event ticketing platforms, or contactless payment solutions, you'll learn how to implement professional-grade QR code functionality in your .NET applications.

Quickstart: One-Line QR Code Creation with IronBarcode

Ready to generate a QR Code fast? Here’s how you can use IronBarcode’s QRCodeWriter API to produce a QR code in just one line of code—customization is optional but powerful.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. Copy and run this code snippet.

    var qr = QRCodeWriter.CreateQrCode("https://ironsoftware.com/", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium); qr.SaveAsPng("MyQR.png");
  3. Deploy to test on your live environment

    Start using IronBarcode in your project today with a free trial
    arrow pointer

How Do I Install a QR Code Library in C#?

Commencez à utiliser IronBarcode dans votre projet aujourd'hui avec un essai gratuit.

Première étape :
green arrow pointer

Install IronBarcode using the NuGet Package Manager with this simple command:

Install-Package BarCode

Install via NuGet

Alternatively, download the IronBarcode DLL directly and add it as a reference to your project.

Import Required Namespaces

Add these namespaces to access IronBarcode's QR code generation features:

using IronBarCode;
using System;
using System.Drawing;
using System.Linq;
using IronBarCode;
using System;
using System.Drawing;
using System.Linq;
Imports IronBarCode
Imports System
Imports System.Drawing
Imports System.Linq
$vbLabelText   $csharpLabel

How Can I Create a Simple QR Code in C#?

Generate a QR code with just one line of code using IronBarcode's CreateQrCode method:

using IronBarCode;

// Generate a QR code with text content
var qrCode = QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium);
qrCode.SaveAsPng("MyQR.png");
using IronBarCode;

// Generate a QR code with text content
var qrCode = QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium);
qrCode.SaveAsPng("MyQR.png");
Imports IronBarCode

' Generate a QR code with text content
Private qrCode = QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium)
qrCode.SaveAsPng("MyQR.png")
$vbLabelText   $csharpLabel

The CreateQrCode method accepts three parameters:

  • Text content: The data to encode (supports URLs, text, or any string data)
  • Size: Pixel dimensions for the square QR code (500x500 in this example)
  • Error correction: Determines readability in suboptimal conditions (Low, Medium, Quartile, or High)

Higher error correction levels enable QR codes to remain readable even when partially damaged or obscured, though they result in denser patterns with more data modules.

Standard QR code generated with IronBarcode in C# A basic QR code containing "hello world" text, generated at 500x500 pixels with medium error correction

How Do I Add a Logo to My QR Code?

Embedding logos in QR codes enhances brand recognition while maintaining scannability. IronBarcode automatically positions and sizes logos to preserve QR code integrity:

using IronBarCode;
using IronSoftware.Drawing;

// Load logo image
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");

// Create QR code with embedded logo
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Customize appearance
myQRCodeWithLogo.ResizeTo(500, 500).SetMargins(10).ChangeBarCodeColor(Color.DarkGreen);

// Save the branded QR code
myQRCodeWithLogo.SaveAsPng("myQRWithLogo.png");
using IronBarCode;
using IronSoftware.Drawing;

// Load logo image
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");

// Create QR code with embedded logo
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Customize appearance
myQRCodeWithLogo.ResizeTo(500, 500).SetMargins(10).ChangeBarCodeColor(Color.DarkGreen);

// Save the branded QR code
myQRCodeWithLogo.SaveAsPng("myQRWithLogo.png");
Imports IronBarCode
Imports IronSoftware.Drawing

' Load logo image
Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")

' Create QR code with embedded logo
Private myQRCodeWithLogo As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo)

' Customize appearance
myQRCodeWithLogo.ResizeTo(500, 500).SetMargins(10).ChangeBarCodeColor(Color.DarkGreen)

' Save the branded QR code
myQRCodeWithLogo.SaveAsPng("myQRWithLogo.png")
$vbLabelText   $csharpLabel

The CreateQrCodeWithLogo method intelligently handles logo placement by:

  • Automatically sizing the logo to maintain QR code readability
  • Positioning it within the quiet zone to avoid data corruption
  • Preserving the logo's original colors when changing QR code colors

This approach ensures your branded QR codes remain fully functional across all scanning devices and applications.

QR code with embedded Visual Studio logo QR code featuring the Visual Studio logo, demonstrating IronBarcode's automatic logo sizing and positioning

How Can I Export QR Codes to Different Formats?

IronBarcode supports multiple export formats for different use cases. Export your QR codes as images, PDFs, or HTML files:

using IronBarCode;
using System.Drawing;

// Create QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply custom styling
myQRCodeWithLogo.ChangeBarCodeColor(Color.DarkGreen);

// Export to multiple formats
myQRCodeWithLogo.SaveAsPdf("MyQRWithLogo.pdf");      // PDF document
myQRCodeWithLogo.SaveAsHtmlFile("MyQRWithLogo.html"); // Standalone HTML
myQRCodeWithLogo.SaveAsPng("MyQRWithLogo.png");       // PNG image
myQRCodeWithLogo.SaveAsJpeg("MyQRWithLogo.jpg");      // JPEG image
using IronBarCode;
using System.Drawing;

// Create QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply custom styling
myQRCodeWithLogo.ChangeBarCodeColor(Color.DarkGreen);

// Export to multiple formats
myQRCodeWithLogo.SaveAsPdf("MyQRWithLogo.pdf");      // PDF document
myQRCodeWithLogo.SaveAsHtmlFile("MyQRWithLogo.html"); // Standalone HTML
myQRCodeWithLogo.SaveAsPng("MyQRWithLogo.png");       // PNG image
myQRCodeWithLogo.SaveAsJpeg("MyQRWithLogo.jpg");      // JPEG image
Imports IronBarCode
Imports System.Drawing

' Create QR code with logo
Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")
Private myQRCodeWithLogo As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo)

' Apply custom styling
myQRCodeWithLogo.ChangeBarCodeColor(Color.DarkGreen)

' Export to multiple formats
myQRCodeWithLogo.SaveAsPdf("MyQRWithLogo.pdf") ' PDF document
myQRCodeWithLogo.SaveAsHtmlFile("MyQRWithLogo.html") ' Standalone HTML
myQRCodeWithLogo.SaveAsPng("MyQRWithLogo.png") ' PNG image
myQRCodeWithLogo.SaveAsJpeg("MyQRWithLogo.jpg") ' JPEG image
$vbLabelText   $csharpLabel

Each format serves specific purposes:

  • PDF: Ideal for printable documents and reports
  • HTML: Perfect for web integration without external dependencies
  • PNG/JPEG: Standard image formats for versatile usage

How Do I Verify QR Code Readability After Customization?

Color modifications and logo additions can impact QR code scannability. Use the Verify() method to ensure your customized QR codes remain readable:

using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Drawing;

// Generate QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myVerifiedQR = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply light color (may affect readability)
myVerifiedQR.ChangeBarCodeColor(Color.LightBlue);

// Verify the QR code can still be scanned
if (!myVerifiedQR.Verify())
{
    Console.WriteLine("LightBlue is not dark enough to be read accurately. Let's try DarkBlue");
    myVerifiedQR.ChangeBarCodeColor(Color.DarkBlue);
}

// Save verified QR code
myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html");

// Open in default browser
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
    FileName = "MyVerifiedQR.html",
    UseShellExecute = true
});
using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Drawing;

// Generate QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myVerifiedQR = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply light color (may affect readability)
myVerifiedQR.ChangeBarCodeColor(Color.LightBlue);

// Verify the QR code can still be scanned
if (!myVerifiedQR.Verify())
{
    Console.WriteLine("LightBlue is not dark enough to be read accurately. Let's try DarkBlue");
    myVerifiedQR.ChangeBarCodeColor(Color.DarkBlue);
}

// Save verified QR code
myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html");

// Open in default browser
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
    FileName = "MyVerifiedQR.html",
    UseShellExecute = true
});
Imports IronBarCode
Imports IronSoftware.Drawing
Imports System
Imports System.Drawing

' Generate QR code with logo
Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")
Private myVerifiedQR As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo)

' Apply light color (may affect readability)
myVerifiedQR.ChangeBarCodeColor(Color.LightBlue)

' Verify the QR code can still be scanned
If Not myVerifiedQR.Verify() Then
	Console.WriteLine("LightBlue is not dark enough to be read accurately. Let's try DarkBlue")
	myVerifiedQR.ChangeBarCodeColor(Color.DarkBlue)
End If

' Save verified QR code
myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html")

' Open in default browser
System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo With {
	.FileName = "MyVerifiedQR.html",
	.UseShellExecute = True
})
$vbLabelText   $csharpLabel

The Verify() method performs a comprehensive scan test on your QR code. This ensures compatibility across different scanning devices and lighting conditions before deployment.

Verified QR code with dark blue coloring and Visual Studio logo A successfully verified QR code in dark blue, demonstrating proper contrast for reliable scanning

How Can I Encode Binary Data in QR Codes?

QR codes excel at storing binary data efficiently. This capability enables advanced applications like encrypted data transfer, file sharing, and IoT device configuration:

using IronBarCode;
using System;
using System.Linq;

// Convert string to binary data
byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/");

// Create QR code from binary content
QRCodeWriter.CreateQrCode(binaryData, 500).SaveAsPng("MyBinaryQR.png");

// Read and verify binary data integrity
var myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First();

// Confirm data matches original
if (binaryData.SequenceEqual(myReturnedData.BinaryValue))
{
    Console.WriteLine("Binary Data Read and Written Perfectly");
}
else
{
    throw new Exception("Data integrity check failed");
}
using IronBarCode;
using System;
using System.Linq;

// Convert string to binary data
byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/");

// Create QR code from binary content
QRCodeWriter.CreateQrCode(binaryData, 500).SaveAsPng("MyBinaryQR.png");

// Read and verify binary data integrity
var myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First();

// Confirm data matches original
if (binaryData.SequenceEqual(myReturnedData.BinaryValue))
{
    Console.WriteLine("Binary Data Read and Written Perfectly");
}
else
{
    throw new Exception("Data integrity check failed");
}
Imports IronBarCode
Imports System
Imports System.Linq

' Convert string to binary data
Private binaryData() As Byte = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/")

' Create QR code from binary content
QRCodeWriter.CreateQrCode(binaryData, 500).SaveAsPng("MyBinaryQR.png")

' Read and verify binary data integrity
Dim myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First()

' Confirm data matches original
If binaryData.SequenceEqual(myReturnedData.BinaryValue) Then
	Console.WriteLine("Binary Data Read and Written Perfectly")
Else
	Throw New Exception("Data integrity check failed")
End If
$vbLabelText   $csharpLabel

Binary encoding in QR codes offers several advantages:

  • Efficiency: Stores data in compact binary format
  • Versatility: Handles any data type (files, encrypted content, serialized objects)
  • Integrity: Preserves exact byte sequences without encoding issues

This feature distinguishes IronBarcode from basic QR code libraries, enabling sophisticated data exchange scenarios in your applications.

QR code containing binary encoded data QR code storing binary data, demonstrating IronBarcode's advanced encoding capabilities

How Do I Read QR Codes in C#?

IronBarcode provides flexible QR code reading capabilities. Here's the simplest approach:

using IronBarCode;
using System;
using System.Linq;

// Read QR code with optimized settings
BarcodeResults result = BarcodeReader.Read("QR.png", new BarcodeReaderOptions() { 
    ExpectBarcodeTypes = BarcodeEncoding.QRCode 
});

// Extract and display the decoded value
if (result != null && result.Any())
{
    Console.WriteLine(result.First().Value);
}
else
{
    Console.WriteLine("No QR codes found in the image.");
}
using IronBarCode;
using System;
using System.Linq;

// Read QR code with optimized settings
BarcodeResults result = BarcodeReader.Read("QR.png", new BarcodeReaderOptions() { 
    ExpectBarcodeTypes = BarcodeEncoding.QRCode 
});

// Extract and display the decoded value
if (result != null && result.Any())
{
    Console.WriteLine(result.First().Value);
}
else
{
    Console.WriteLine("No QR codes found in the image.");
}
Imports IronBarCode
Imports System
Imports System.Linq

' Read QR code with optimized settings
Private result As BarcodeResults = BarcodeReader.Read("QR.png", New BarcodeReaderOptions() With {.ExpectBarcodeTypes = BarcodeEncoding.QRCode})

' Extract and display the decoded value
If result IsNot Nothing AndAlso result.Any() Then
	Console.WriteLine(result.First().Value)
Else
	Console.WriteLine("No QR codes found in the image.")
End If
$vbLabelText   $csharpLabel

For more complex scenarios requiring fine-tuned control:

using IronBarCode;
using System;
using System.Linq;

// Configure advanced reading options
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Faster,           // Optimize for speed
    ExpectMultipleBarcodes = false,        // Single QR code expected
    ExpectBarcodeTypes = BarcodeEncoding.QRCode, // QR codes only
    Multithreaded = true,                  // Enable parallel processing
    MaxParallelThreads = 4,                // Utilize multiple CPU cores
    RemoveFalsePositive = true,            // Filter out false detections
    ImageFilters = new ImageFilterCollection() // Apply preprocessing
    {
        new AdaptiveThresholdFilter(),    // Handle varying lighting
        new ContrastFilter(),              // Enhance contrast
        new SharpenFilter()                // Improve edge definition
    }
};

// Read with advanced configuration
BarcodeResults result = BarcodeReader.Read("QR.png", options);
using IronBarCode;
using System;
using System.Linq;

// Configure advanced reading options
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Faster,           // Optimize for speed
    ExpectMultipleBarcodes = false,        // Single QR code expected
    ExpectBarcodeTypes = BarcodeEncoding.QRCode, // QR codes only
    Multithreaded = true,                  // Enable parallel processing
    MaxParallelThreads = 4,                // Utilize multiple CPU cores
    RemoveFalsePositive = true,            // Filter out false detections
    ImageFilters = new ImageFilterCollection() // Apply preprocessing
    {
        new AdaptiveThresholdFilter(),    // Handle varying lighting
        new ContrastFilter(),              // Enhance contrast
        new SharpenFilter()                // Improve edge definition
    }
};

// Read with advanced configuration
BarcodeResults result = BarcodeReader.Read("QR.png", options);
Imports IronBarCode
Imports System
Imports System.Linq

' Configure advanced reading options
Private options As New BarcodeReaderOptions With {
	.Speed = ReadingSpeed.Faster,
	.ExpectMultipleBarcodes = False,
	.ExpectBarcodeTypes = BarcodeEncoding.QRCode,
	.Multithreaded = True,
	.MaxParallelThreads = 4,
	.RemoveFalsePositive = True,
	.ImageFilters = New ImageFilterCollection() From {
		New AdaptiveThresholdFilter(),
		New ContrastFilter(),
		New SharpenFilter()
	}
}

' Read with advanced configuration
Private result As BarcodeResults = BarcodeReader.Read("QR.png", options)
$vbLabelText   $csharpLabel

These advanced reading options enable reliable QR code detection in challenging conditions like poor lighting, image distortion, or low-quality prints.

What's Next for QR Code Development?

Now that you've mastered QR code generation with IronBarcode, explore these advanced topics:

Download Resources

Access the complete source code and examples:

API Documentation

Explore the complete feature set in the API reference:

Alternative: IronQR for Advanced QR Applications

For projects requiring cutting-edge QR code capabilities, consider IronQR--Iron Software's specialized QR code library featuring machine learning-powered reading with 99.99% accuracy and advanced generation options.

Ready to implement QR codes in your .NET application? Start your free trial or download IronBarcode today.

Questions Fréquemment Posées

Comment générer un code QR en C# ?

Vous pouvez générer un code QR en C# en utilisant la méthode IronBarcode's QRCodeWriter.CreateQrCode(). Cette méthode vous permet de passer votre contenu, taille, et niveau de correction d'erreur pour créer efficacement un code QR.

Quels formats d'image les codes QR peuvent-ils être exportés ?

Avec IronBarcode, vous pouvez exporter des codes QR vers divers formats, y compris PNG, JPEG, PDF et HTML. Des méthodes comme SaveAsPng(), SaveAsJpeg(), SaveAsPdf(), et SaveAsHtmlFile() sont disponibles à cet effet.

Comment puis-je ajouter un logo d'entreprise à un code QR ?

IronBarcode fournit la méthode CreateQrCodeWithLogo(), où vous pouvez passer un objet QRCodeLogo contenant l'image de votre logo. La bibliothèque garantit que le logo est correctement dimensionné et positionné pour que le code QR reste lisible.

Qu'est-ce que la correction d'erreur de code QR et quel niveau choisir ?

La correction d'erreur dans les codes QR leur permet de rester scannables même s'ils sont partiellement endommagés. IronBarcode offre quatre niveaux : Faible (7%), Moyen (15%), Quartile (25%) et Élevé (30%). Moyen est adapté pour la plupart des usages, tandis qu'Élevé est idéal pour les environnements difficiles.

Comment vérifier la lisibilité d'un code QR personnalisé ?

Vous pouvez utiliser la méthode Verify() sur un objet GeneratedBarcode pour vous assurer que votre code QR personnalisé reste scannable après des modifications telles que des changements de couleur ou des ajouts de logo.

Les données binaires peuvent-elles être encodées dans les codes QR ?

Oui, la méthode CreateQrCode() d'IronBarcode prend en charge l'encodage de tableaux d'octets, vous permettant de stocker des données binaires telles que des fichiers ou du contenu crypté au sein des codes QR.

Comment lire des codes QR à partir d'images en C# ?

Pour lire des codes QR à partir d'images en C#, utilisez la méthode BarcodeReader.Read() d'IronBarcode. Pour une performance optimisée, spécifiez BarcodeEncoding.QRCode dans le BarcodeReaderOptions.

Quelle est la capacité de données maximale d'un code QR ?

Les codes QR générés par IronBarcode peuvent contenir jusqu'à 2 953 octets, 4 296 caractères alphanumériques ou 7 089 chiffres, selon le niveau de correction d'erreur sélectionné.

Comment puis-je changer la couleur d'un code QR tout en assurant qu'il reste scannable ?

La méthode ChangeBarCodeColor() dans IronBarcode vous permet de changer la couleur d'un code QR. Utilisez toujours la méthode Verify() par la suite pour confirmer que la lisibilité du code QR n'est pas affectée par le changement de couleur.

Quelles fonctionnalités offre une bibliothèque spécialisée de code QR ?

IronQR, une bibliothèque spécialisée d'Iron Software, inclut des fonctionnalités avancées telles que la lecture de code QR alimentée par l'apprentissage automatique avec une précision de 99,99%, et des capacités de génération robuste adaptées aux applications complexes.

Jacob Mellor, Directeur technique @ Team Iron
Directeur technique

Jacob Mellor est directeur technique chez Iron Software et un ingénieur visionnaire pionnier dans la technologie des PDF en C#. En tant que développeur original derrière la base de code principale d'Iron Software, il a façonné l'architecture du produit de l'entreprise depuis sa création, ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 1,935,276 | Version : 2025.11 vient de sortir