.NET (1322)
Children categories
Spire.Email allows receiving email messages with POP3 client and IMAP client. The following examples demonstrate how to retrieve an email using both POP3 and IMAP clients and save it to disk in C# and VB.NET.
Use POP3 client
using Spire.Email;
using Spire.Email.Pop3;
using System;
using System.Globalization;
namespace ReceiveAndSaveEmailByUsingPOP3client
{
class Program
{
static void Main(string[] args)
{
//Create a POP3 client
Pop3Client pop = new Pop3Client();
//Set host, username, password etc. for the client
pop.Host = "outlook.office365.com";
pop.Username = "LeonDavisLD@outlook.com";
pop.Password = "password";
pop.Port = 995;
pop.EnableSsl = true;
//Connect the server
pop.Connect();
//Get the first message by its sequence number
MailMessage message = pop.GetMessage(1);
//Parse the message
Console.WriteLine("------------------ HEADERS ---------------");
Console.WriteLine("From : " + message.From.ToString());
Console.WriteLine("To : " + message.To.ToString());
Console.WriteLine("Date : " + message.Date.ToString(CultureInfo.InvariantCulture));
Console.WriteLine("Subject: " + message.Subject);
Console.WriteLine("------------------- BODY -----------------");
Console.WriteLine(message.BodyText);
Console.WriteLine("------------------- END ------------------");
//Save the message to disk using its subject as file name
message.Save(message.Subject + ".eml", MailMessageFormat.Eml);
Console.WriteLine("Message Saved.");
Console.ReadKey();
}
}
}
Imports Spire.Email
Imports Spire.Email.Pop3
Imports System.Globalization
Namespace ReceiveAndSaveEmailByUsingPOP3client
Class Program
Private Shared Sub Main(args As String())
'Create a POP3 client
Dim pop As New Pop3Client()
'Set host, username, password etc. for the client
pop.Host = "outlook.office365.com"
pop.Username = "LeonDavisLD@outlook.com"
pop.Password = "password"
pop.Port = 995
pop.EnableSsl = True
'Connect the server
pop.Connect()
'Get the first message by its sequence number
Dim message As MailMessage = pop.GetMessage(1)
'Parse the message
Console.WriteLine("------------------ HEADERS ---------------")
Console.WriteLine("From : " + message.From.ToString())
Console.WriteLine("To : " + message.[To].ToString())
Console.WriteLine("Date : " + message.[Date].ToString(CultureInfo.InvariantCulture))
Console.WriteLine("Subject: " + message.Subject)
Console.WriteLine("------------------- BODY -----------------")
Console.WriteLine(message.BodyText)
Console.WriteLine("------------------- END ------------------")
'Save the message to disk using its subject as file name
message.Save(message.Subject + ".eml", MailMessageFormat.Eml)
Console.WriteLine("Message Saved.")
Console.ReadKey()
End Sub
End Class
End Namespace
Use IMAP client
using Spire.Email;
using Spire.Email.IMap;
using System;
using System.Globalization;
namespace ReceiveAndSaveEmailByUsingIMAPclient
{
class Program
{
static void Main(string[] args)
{
//Create an IMAP client
ImapClient imap = new ImapClient();
// Set host, username, password etc. for the client
imap.Host = "outlook.office365.com";
imap.Port = 143;
imap.Username = "LeonDavisLD@outlook.com";
imap.Password = "password";
imap.ConnectionProtocols = ConnectionProtocols.Ssl;
//Connect the server
imap.Connect();
//Select Inbox folder
imap.Select("Inbox");
//Get the first message by its sequence number
MailMessage message = imap.GetFullMessage(1);
//Parse the message
Console.WriteLine("------------------ HEADERS ---------------");
Console.WriteLine("From : " + message.From.ToString());
Console.WriteLine("To : " + message.To.ToString());
Console.WriteLine("Date : " + message.Date.ToString(CultureInfo.InvariantCulture));
Console.WriteLine("Subject: " + message.Subject);
Console.WriteLine("------------------- BODY -----------------");
Console.WriteLine(message.BodyText);
Console.WriteLine("------------------- END ------------------");
//Save the message to disk using its subject as file name
message.Save(message.Subject + ".eml", MailMessageFormat.Eml);
Console.WriteLine("Message Saved.");
Console.ReadKey();
}
}
}
Imports Spire.Email
Imports Spire.Email.IMap
Imports System.Globalization
Namespace ReceiveAndSaveEmailByUsingIMAPclient
Class Program
Private Shared Sub Main(args As String())
'Create an IMAP client
Dim imap As New ImapClient()
' Set host, username, password etc. for the client
imap.Host = "outlook.office365.com"
imap.Port = 143
imap.Username = "LeonDavisLD@outlook.com"
imap.Password = "password"
imap.ConnectionProtocols = ConnectionProtocols.Ssl
'Connect the server
imap.Connect()
'Select Inbox folder
imap.[Select]("Inbox")
'Get the first message by its sequence number
Dim message As MailMessage = imap.GetFullMessage(1)
'Parse the message
Console.WriteLine("------------------ HEADERS ---------------")
Console.WriteLine("From : " + message.From.ToString())
Console.WriteLine("To : " + message.[To].ToString())
Console.WriteLine("Date : " + message.[Date].ToString(CultureInfo.InvariantCulture))
Console.WriteLine("Subject: " + message.Subject)
Console.WriteLine("------------------- BODY -----------------")
Console.WriteLine(message.BodyText)
Console.WriteLine("------------------- END ------------------")
'Save the message to disk using its subject as file name
message.Save(message.Subject + ".eml", MailMessageFormat.Eml)
Console.WriteLine("Message Saved.")
Console.ReadKey()
End Sub
End Class
End Namespace
Screenshot:

Following code snippets demonstrate how to send an email with HTML body using Spire.Email in C# and VB.NET.
Step 1: Create an instance of MailMessage class and specify sender and recipient in its constructor.
MailAddress addressFrom = new MailAddress("jack.du@e-iceblue.com", "Jack Du");
MailAddress addressTo = new MailAddress("susanwong32@outlook.com");
MailMessage message = new MailMessage(addressFrom, addressTo);
Step 2: Set the creation date, subject and html body of the message.
message.Date = DateTime.Now;
message.Subject = "Sending Email with HTML Body";
string htmlString = @"<html>
<body>
<p>Dear Ms. Susan,</p>
<p>Thank you for your letter of yesterday inviting me to come for an interview on Friday afternoon, 5th July, at 2:30.
I shall be happy to be there as requested and will bring my diploma and other papers with me.</p>
<p>Sincerely,<br>-Jack</br></p>
</body>
</html>
";
message.BodyHtml = htmlString;
Step 3: Create a SmtpClient instance, set its properties, and send the email using SendOne() medthod.
SmtpClient client= new SmtpClient(); client.Host = "smtp.outlook.com"; client.Port = 587; client.Username = addressFrom.Address; client.Password = "password"; client.ConnectionProtocols = ConnectionProtocols.Ssl; client.SendOne(message);
Output:

Full Code:
MailAddress addressFrom = new MailAddress("jack.du@e-iceblue.com", "Jack Du");
MailAddress addressTo = new MailAddress("susanwong32@outlook.com");
MailMessage message = new MailMessage(addressFrom, addressTo);
message.Date = DateTime.Now;
message.Subject = "Sending Email with HTML Body";
string htmlString = @"<html>
<body>
<p>Dear Ms. Susan,</p>
<p>Thank you for your letter of yesterday inviting me to come for an interview on Friday afternoon, 5th July, at 2:30.
I shall be happy to be there as requested and will bring my diploma and other papers with me.</p>
<p>Sincerely,<br>-Jack</br></p>
</body>
</html>
";
message.BodyHtml = htmlString;
SmtpClient client= new SmtpClient();
client.Host = "smtp.outlook.com";
client.Port = 587;
client.Username = addressFrom.Address;
client.Password = "password";
client.ConnectionProtocols = ConnectionProtocols.Ssl;
client.SendOne(message);
Console.WriteLine("Sent Successfully!");
Console.Read();
using Spire.Email;
using Spire.Email.IMap;
using Spire.Email.Smtp;
using System;
namespace SendEmailwithHTMLBody
{
class Program
{
static void Main(string[] args)
{
MailAddress addressFrom = new MailAddress("jack.du@e-iceblue.com", "Jack Du");
MailAddress addressTo = new MailAddress("susanwong32@outlook.com");
MailMessage message = new MailMessage(addressFrom, addressTo);
message.Date = DateTime.Now;
message.Subject = "Sending Email with HTML Body";
string htmlString = @"<html>
<body>
<p>Dear Ms. Susan,</p>
<p>Thank you for your letter of yesterday inviting me to come for an interview on Friday afternoon, 5th July, at 2:30.
I shall be happy to be there as requested and will bring my diploma and other papers with me.</p>
<p>Sincerely,<br>-Jack</br></p>
</body>
</html>
";
message.BodyHtml = htmlString;
SmtpClient client = new SmtpClient();
client.Host = "smtp.outlook.com";
client.Port = 587;
client.Username = addressFrom.Address;
client.Password = "password";
client.ConnectionProtocols = ConnectionProtocols.Ssl;
client.SendOne(message);
Console.WriteLine("Sent Successfully!");
Console.Read();
}
}
}

Sending emails with file attachments using C# is a common requirement in .NET development — whether it’s for sharing reports, invoices, or log files. While .NET’s built-in namespaces offer basic email support, things can become difficult when dealing with attachments, encoding, or dynamically generated content.
To simplify these tasks, this guide introduces how to send an email with attachment in C# using Spire.Email for .NET. We’ll cover how to attach files from disk, memory streams, or byte arrays, and walk you through configuring SMTP clients — including settings for Outlook. Whether you're working on a C# console app, an ASP.NET project, or other types of .NET applications, this guide provides practical examples to help you get started.
Table of Contents
- 1. Getting Started: Sending Emails in C# Using Spire.Email
- 2. Send Email with File Attachment from Disk in C#
- 3. Attach Files from MemoryStream or Byte Array
- 4. Send Email with Outlook SMTP in C#
- 5. Real-World Example
- 6. Troubleshooting Tips and Best Practices
- 7. Summary and Next Steps
- 8. Frequently Asked Questions (FAQ)
1. Getting Started: Sending Emails in C# Using Spire.Email
Spire.Email for .NET is a professional email library that enables .NET applications to create, send, receive, and manage emails without relying on Outlook or other third-party clients. It supports SMTP, POP3, and IMAP protocols, and handles attachments, HTML formatting, and inline resources with ease.
Installation
You can install the library via NuGet with the following command:
Install-Package Spire.Email
Download Spire.Email for .NET from the official page and install manually.
2. Send Email with File Attachment from Disk in C#
Sending file attachments via email is a common requirement in many C# applications—especially when automating tasks like batch reporting or file distribution. This section demonstrates how to send an email with a PDF file attached from the local disk using Spire.Email.
Key steps include:
- Setting up sender and recipient addresses
- Composing an HTML-formatted email body
- Adding a file attachment using the Attachment class
- Configuring and authenticating the SMTP client
This hands-on example provides a clear overview of how to send emails with attachments in C#, using just a few lines of code.
Example Code
using Spire.Email;
using Spire.Email.Smtp;
class Program
{
static void Main()
{
try
{
// Create MailAddress objects for sender, recipient, and CC
MailAddress addressFrom = new MailAddress("user@yourcompany.com", "Sender Name");
MailAddress addressTo = new MailAddress("recipient@yourcompany.com", "Recipient Name");
MailAddress addressCc = new MailAddress("copy@yourcompany.com", "Cc Name");
// Create a new MailMessage and set From and To addresses
MailMessage message = new MailMessage(addressFrom, addressTo);
// Add CC recipient
message.Cc.Add(addressCc);
// Set the email subject and body
message.Subject = "Monthly Report - June 2025";
message.BodyHtml = "<div style='font-family:Segoe UI, sans-serif; font-size:14px; color:#333; line-height:1.6;'>" +
"<p>Dear all,</p>" +
"<p>Please find the <strong style='color:#2E86C1;'>monthly report</strong> attached.</p>" +
"<p>If you have any questions, feel free to reach out at your convenience.</p>" +
"<p style='margin-top:30px;'>Best regards,</p>" +
"<p style='font-style:italic; color:#555;'>Sender Name</p>" +
"</div>";
// Add an attachment from file
String filePath = @"Sample.pdf";
Attachment attachment = new Attachment(filePath);
message.Attachments.Add(attachment);
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.yourcompany.com";
smtp.Port = 587;
smtp.Username = "your_username";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Attempt to send the email
smtp.SendOne(message);
// If no exception is thrown, email was sent successfully
Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
// If an error occurs, print the error message
Console.WriteLine("Failed to send email.");
Console.WriteLine("Error: " + ex.Message);
}
}
}
The following screenshot shows the result of sending a simple email with a PDF attachment using the C# code above:

You may also like: Extract and Delete Email Attachments Using C#
3. Attach Files from MemoryStream or Byte Array to an Email
In many scenarios — such as exporting a document or image on the fly — you may need to send an email with attachment from a memory stream using C#, without saving the file to disk. Spire.Email makes this easy by allowing you to attach files directly from a MemoryStream or byte array.
Example: Attach a PDF from MemoryStream
using System.IO;
using Spire.Email;
String filePath = @"Sample.pdf";
MemoryStream stream = new MemoryStream(File.ReadAllBytes(filePath));
Attachment attachment = new Attachment(stream, Path.GetFileName(filePath);
message.Attachments.Add(attachment);
You can also attach from a byte array:
String filePath = @"Sample.pdf";
byte[] fileBytes = File.ReadAllBytes(filePath);
MemoryStream memStream = new MemoryStream(fileBytes);
Attachment imgAttachment = new Attachment(memStream, Path.GetFileName(filePath));
message.Attachments.Add(imgAttachment);
This is especially useful in web applications or services where you generate documents dynamically.
When creating an Attachment object using a stream, make sure the file name includes a valid extension (e.g., .pdf, .xlsx) to ensure the correct MIME type is recognized.
4. Send Email with Outlook SMTP in C#
If you're using an Outlook or Microsoft 365 account, you can send emails through their SMTP server using Spire.Email.
Outlook SMTP Configuration
smtp.Host = "smtp.office365.com";
smtp.Port = 587;
smtp.Username = "your_outlook_email@domain.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
Spire.Email fully supports TLS and STARTTLS, ensuring secure connections to Microsoft’s mail servers.
If you want to send emails in Outlook MSG format, please refer to: How to Send Outlook MSG Emails with Attachments in C#
5. Real-World Example: Sending C# Emails with Attachments and Dynamic Content
In a real-world business scenario, you often need to send project progress reports to multiple recipients, each with personalized content. Using Spire.Email for .NET, you can easily send individual emails with attachments and customized greetings—all within a simple C# application.
The example below demonstrates how to send a project status report to multiple clients, using dynamic recipient names in the greeting line and attaching PDF or Excel documents.
Full Code Example
using Spire.Email;
using Spire.Email.Smtp;
class Program
{
static void Main()
{
// Define sender
MailAddress addressFrom = new MailAddress("user@yourcompany.com", "Sender");
// Define recipient list with name and email
List<MailAddress> recipients = new List<MailAddress>
{
new MailAddress("sales@clientA.com", "Sales Team A"),
new MailAddress("manager@clientB.com", "Manager B"),
new MailAddress("support@clientC.com", "Support Team C")
};
// Attachments to be included
string[] attachmentFiles = { @"Sample.pdf", @"Sample.xlsx" };
// Configure SMTP once
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.yourcompany.com";
smtp.Port = 587;
smtp.Username = "your_username";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Send email to each recipient individually
foreach (var recipient in recipients)
{
try
{
// Create a new message for each recipient
MailMessage message = new MailMessage(addressFrom, recipient);
message.Subject = "Project Status Update - Q2 2025";
// Use the display name in the greeting
string greetingName = string.IsNullOrEmpty(recipient.DisplayName)
? "team"
: recipient.DisplayName;
// Mail content
message.BodyHtml = $@"
<div style='font-family:Segoe UI, sans-serif; font-size:14px; color:#333; line-height:1.6;'>
<p>Dear {greetingName},</p>
<p>Please find attached the <strong>Q2 2025 Project Status Report</strong>, covering:</p>
<ul style='padding-left:18px; margin:0;'>
<li>Milestones achieved</li>
<li>Pending tasks</li>
<li>Key insights</li>
</ul>
<p>If you have any questions or would like to discuss the details, feel free to reach out.</p>
<p>Best regards,<br><strong>Sender</strong></p>
</div>";
// Send the message
smtp.SendOne(message);
Console.WriteLine($"Email sent to {recipient.Address}.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to send email to {recipient.Address}.");
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
This example is applicable to C# console applications, ASP.NET apps, or any .NET project requiring email functionality.
Below is a sample of the personalized project status email generated in the complete working example:

6. Troubleshooting Tips and Best Practices
Here are some common issues developers encounter when sending email with attachments in C#:
- Authentication errors: Ensure your SMTP credentials are correct and SSL/TLS is properly set.
- Blocked ports: Many hosting environments block port 25. Use 465 (SSL) or 587 (TLS) instead.
- Attachment size limits: Most SMTP servers restrict attachment size. Consider compressing or splitting files.
- Secure credential handling: Avoid hardcoding sensitive credentials in code. Use secure storage or environment variables.
- MIME type issues: If you're attaching files from byte arrays or memory streams, make sure the attachment name includes a valid extension so the MIME type can be correctly inferred.
By using Spire.Email, you can handle encoding, multi-format attachments, and protocol security with ease—without writing verbose code.
7. Summary and Next Steps
In this tutorial, we’ve shown how to send an email with attachment in C# using Spire.Email for .NET. From basic file attachments to advanced scenarios involving memory streams or Outlook SMTP integration, Spire.Email provides a streamlined and developer-friendly API.
If you're looking for a way to simplify email functionality in your .NET applications, Spire.Email is worth exploring. You can apply for a free temporary license and try it in your own projects.
8. Frequently Asked Questions (FAQ)
❓ How do I attach a file in an email using C#?
You can use the Attachment class from Spire.Email to attach a file like this:
message.Attachments.Add(new Attachment(@"file.pdf"));
You can also attach files from a MemoryStream or byte array if the file is generated in memory.
❓ How can I send an email with an attached file?
Use the SmtpClient.SendOne() method in Spire.Email to send the message after adding attachments with MailMessage.Attachments.Add(). Ensure your SMTP configuration and authentication details are correct.
❓ Can I send an email with attachment in .NET Core?
Yes. Spire.Email for .NET supports .NET Core, .NET Standard, .NET 5+, .NET Framework, ASP.NET, MonoAndroid, Xamarin.iOS, and works with both C# and VB.NET.
❓ How do I send an email with Excel attachment in C#?
You can attach Excel files like .xlsx or .xls just like any other file:
message.Attachments.Add(new Attachment(@"report.xlsx"));
Make sure the file path is valid and the file is accessible to the application.
We have already demonstrated how to generate 1D barcode and 2D barcodes by using Spire.Barcode. This article will demonstrate how to scan the barcode images with Spire.Barcode. Spire.Barcode supports scanning the barcode image in .bmp, .png and .jpg image format. We will use Spire.Barcode to scan both 1D barcode and 2D barcode for example.
Scan Code39 barcode image:
string[] data = Spire.Barcode.BarcodeScanner.Scan("Code39.png",
Spire.Barcode.BarCodeType.Code39);

Scan QRCode barcode image:
string[] data = Spire.Barcode.BarcodeScanner.Scan("QRCode.png", Spire.Barcode.BarCodeType.QRCode);


When working with Word templates, it's common to replace specific placeholders with real content—like names, dates, or even company logos. Manually updating each instance may take lots of effort and time. Fortunately, you can automate this process using code. In this tutorial, we'll show you how to use C# regex replace to find and replace text in Word documents. You'll learn how to apply regular expressions across the entire document, target specific paragraphs, and even replace matched text with images.
- Before We Start: Install Word Library
- Replace Text in an Entire Word Document
- Replace Text within Specific Paragraph in C#
- Replace Regex Matches with Images
- Replace Text with Regex in VB.NET
- Conclusion
Before We Start: Install Word Library
To make this task easier, we recommend using Spire.Doc for .NET — a powerful Word library designed to automate common document operations such as reading, editing, and converting Word files. With Spire.Doc, performing a C# regex replace in Word documents can be done in just a few lines of code.
You can install the library via NuGet with the following command:
PM> Install-Package Spire.Doc
Alternatively, you can download the Spire.Doc package and install it with custom settings. A free version is also available, ideal for small projects or evaluation purposes.
Use Regex to Replace Text in an Entire Word Document
Let's start with the most common scenario — replacing text throughout the entire Word document. You can use regular expressions to match all patterns like #name or #tel, then replace them with actual values such as a person's name or phone number.
With the help of the Document.Replace() method provided by Spire.Doc, this task becomes incredibly simple. Here's a step-by-step explanation along with sample code to show how to replace text using regex in C#.
Code example - replacing #name with "May" in the entire Word document using C#:
using Spire.Doc;
using System.Text.RegularExpressions;
namespace FindText
{
class Program
{
static void Main(string[] args)
{
// Create an object of Document class and load a Word document
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
// Set the regular expression
Regex regex = new Regex(@"#\w+\b");
// Replace all matches with "May"
doc.Replace(regex, "May");
// Save the document
doc.SaveToFile("/output/replacealloccurences.docx", FileFormat.Docx2013);
}
}
}
Here is a comparison preview of the results before and after using regex to replace text in C#: 
Steps Explained:
- Create a Document instance and load a Word document from files.
- Set the regular expression.
- Replace all matches in the document with Documet.Replace() method.
- Save the updated document.
Apply Regex Replace to a Specific Paragraph in C#
Replacing text across the entire document may seem straightforward, but how can we achieve the same result within a specific paragraph? When you need more precise control, such as performing regex replace only within a paragraph range, you can retrieve the paragraph text and reset its content manually. In code, this means using regular expressions to locate matches within the target paragraph, remove the original text, and insert the replacement.
Let’s first look at a real-world code example — we’ll break down the detailed steps right after.
Code example - replacing #name with "Lily" in the first paragraph using regular expression:
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a template
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
Regex regex = new Regex(@"#\w+\b");
// Get the first paragraph
Paragraph para = doc.Sections[0].Paragraphs[0];
string originalText = para.Text;
if (regex.IsMatch(originalText))
{
string newText = regex.Replace(originalText, "Lily");
// Clear the content and append the new text
para.ChildObjects.Clear();
para.AppendText(newText);
}
// Save the updated document
doc.SaveToFile("/output/replacefirstpara.docx", FileFormat.Docx2013);
}
}
Here is a before-and-after comparison of using regular expressions in C# to replace text in the first paragraph: 
Detailed steps explained:
- Create a Document object and load the Word file.
- Access the target paragraph using Sections[].Paragraphs[] property.
- Get the original text from the paragraph.
- Use a regular expression to find and replace matching text.
- Clear the original content and append the updated text to the paragraph.
- Save the modified document.
Replace Regex Matches with Images in Word Using C#
Now that we’ve covered how to replace text in the entire document or within a single paragraph, let’s move on to something more advanced—replacing text with images. This is often used in practical scenarios like generating reports or company brochures. For instance, you might want to replace a placeholder such as [logo] with your company’s actual logo.
With the help of C# regex replace and Spire.Doc’s image insertion APIs, this task can also be automated. Let’s take a look at a real code example first, then we’ll explain how it works.
Code example – replacing [avatar] with an image:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Text.RegularExpressions;
namespace RegexReplaceWithImage
{
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a Word file from disk
Document document = new Document();
document.LoadFromFile(@"\input\replace template.docx");
// Define a regular expression to match placeholders
Regex regex = new Regex(@"\[\w+\]", RegexOptions.IgnoreCase);
// Find all matches in the document that match the pattern
TextSelection[] selections = document.FindAllPattern(regex);
// Loop through each matched placeholder
foreach (TextSelection selection in selections)
{
// Create a picture object and load the image from disk
DocPicture pic = new DocPicture(document);
pic.LoadImage(@"\avatar-1.png");
// Get the matched text as a single text range
TextRange textRange = selection.GetAsOneRange();
// Get the index of the text range in its parent paragraph
int index = textRange.OwnerParagraph.ChildObjects.IndexOf(textRange);
// Insert the image at the matched position
textRange.OwnerParagraph.ChildObjects.Insert(index, pic);
// Remove the original placeholder text
textRange.OwnerParagraph.ChildObjects.Remove(textRange);
}
// Save the modified document to disk
document.SaveToFile(@"\output\ReplaceTextWithImage.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Here is a before-and-after comparison of replacing text with an image using regex in C#: 
Detailed steps explained:
- Create an object of Document class and read a Word document.
- Define a regular expression to match target content.
- Find all occurrences using Document.FindAllPattern() method.
- Loop through the collection of matches.
- Create a DocPicture instance and load an image.
- Get the matched text as a text range and retrieve its index in the parent paragraph.
- Insert the image at the position and remove the original text.
- Save the Word document as a new file.
Replace Text with Regex in VB.NET
If you're working with VB.NET instead of C#, you can achieve the same result using regular expressions to search and replace text throughout a Word document. The approach is similar—load the file, apply a regex pattern, and update the content. Here's a simple example to get you started.
Imports Spire.Doc
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim doc As New Document()
doc.LoadFromFile("/input/replace template.docx")
Dim regex As New Regex("#\w+\b")
doc.Replace(regex, "Lena")
doc.SaveToFile("/output/regexreplace.docx", FileFormat.Docx2013)
End Sub
End Module
Above is the VB.NET code for replacing text throughout an entire Word document using regular expressions.
If you need to perform other tasks, such as replacing text in specific paragraphs or replacing text with images, you can easily convert the C# code examples into VB.NET using the C# Code ⇆ VB.NET Code Converter — a handy tool developed by the Spire.Doc team.
The Conclusion
With the help of regular expressions, replacing text or even inserting images in Word documents using C# becomes a smooth and efficient process. Whether you're working on templates, reports, or personalized documents, this approach saves time and reduces manual work. Ready to try it out? Download Spire.Doc and get started with a free 30-day trial license—perfect for evaluation and small projects.
Add, Count, Retrieve and Remove Variables in a Word document Using C#
2017-06-22 08:26:33 Written by KoohjiDocument variables are used to preserve macro settings in between macro sessions. Spire.Doc allows adding variables, counting the number of variables, retrieving the name and value of variables, and removing specific variables in a Word document.
Add a Variable
Use the Add method to add a variable to a document. The following example adds a document variable named "A1" with a value of 12 to the document.
using Spire.Doc;
using Spire.Doc.Documents;
namespace ADDVARIABLE
{
class Program
{
static void Main(string[] args)
{
//Instantiate a document object
Document document = new Document();
//Add a section
Section section = document.AddSection();
//Add a paragraph
Paragraph paragraph = section.AddParagraph();
//Add a DocVariable Filed
paragraph.AppendField("A1", FieldType.FieldDocVariable);
//Add a document variable to the DocVariable Filed
document.Variables.Add("A1", "12");
//Update fields
document.IsUpdateFields = true;
//Save and close the document object
document.SaveToFile("AddVariable.docx", FileFormat.Docx2013);
document.Close();
}
}
}

Count the number of Variables
Use the Count property to return the number of variables in a document.
//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;
Console.WriteLine(number);

Retrieve Name and Value of a Variable
Use the GetNameByIndex and GetValueByIndex methods to retrieve the name and value of the variable by index, and the Variables[String Name] to retrieve or set the value of the variable by name.
using Spire.Doc;
using Spire.Doc.Documents;
using System;
namespace COUNTVARIABLE
{
class Program
{
static void Main(string[] args)
{
//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;
Console.WriteLine(number);
}
}
}

Remove a specific Variable
Use the Remove method to remove the variable from the document.
using Spire.Doc;
using System;
namespace RETRIEVEVARIABLE
{
class Program
{
static void Main(string[] args)
{
//Load the document
Document document = new Document("AddVariable.docx");
// Retrieve name of the variable by index
string s1 = document.Variables.GetNameByIndex(0);
// Retrieve value of the variable by index
string s2 = document.Variables.GetValueByIndex(0);
// Retrieve or set value of the variable by name
string s3 = document.Variables["A1"];
Console.WriteLine("{0} {1} {2}", s1, s2, s3);
}
}
}
When we operate the data on an Excel worksheet, we may need to delete text from a cell in a spreadsheet document and sometimes even remove all the contents with format from the cell range. This article will demonstrate how to remove the value and format from Excel Cell range with the help of Spire.XLS.
Step 1: Create an instance of Excel workbook and load the document from file.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Step 2: Get the first worksheet from the workbook.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Set the value as null to remove the original content from the Excel Cell.
sheet.Range["A1"].Value = "";
Step 4: Clear the contents to remove the original content from the Excel Cell.
sheet.Range["A3"].ClearContents();
Step 5: Remove the contents with format from the Excel cell.
sheet.Range["B1"].ClearAll();
Step 6: Save document to file.
workbook.SaveToFile("result.xlsx",FileFormat.Version2010);
Effective screenshot of remove the value and format from Excel Cell range:

Full codes:
using Spire.Xls;
namespace RemoveValue
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Worksheet sheet = workbook.Worksheets[0];
sheet.Range["A1"].Value = "";
sheet.Range["A3"].ClearContents();
sheet.Range["B1"].ClearAll();
workbook.SaveToFile("result.xlsx", FileFormat.Version2010);
}
}
}
The PDF417 barcode, also known as Portable Data File 417 or PDF417 Truncated, is a two-dimensional (2D), high-density symbology capable of encoding text, numbers, files and actual data bytes.
Compaction Modes
The data is encoded using one of three compaction modes: Text compaction mode, Binary compaction mode, and Numeric compaction mode.
- Text: It allows encoding all printable ASCII characters, i.e. values from 32 to 126 inclusive in accordance with ISO/IEC 646, as well as selected control characters such as TAB (horizontal tab ASCII 9), LF (NL line feed, new line ASCII 10) and CR (carriage return ASCII 13).
- Binary: It allows encoding all 256 possible 8-bit byte values. This includes all ASCII characters value from 0 to 127 inclusive and provides for international character set support.
- Numeric: It allows efficient encoding of numeric data strings.
- Auto: It switches between Text, Binary and Numeric modes in order to minimize the number of codewords to be encoded.
PDF417 Error Correction Levels
Error correction allows the symbol to endure some damage without causing loss of data. The error correction level depends on the amount of data that needs to be encoded, the size and the amount of symbol damage that could occur. The error correction levels range from 0 to 8.
| EC Level | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | ||
| EC Codewords Generated | 2 | 4 | 6 | 8 | 16 | 32 | 64 | 128 | 512 | ||
| Data Codewords | 1-40 | 41-160 | 161-320 | 321-863 | |||||||
| Data Bytes Encoded | 1-56 | 57-192 | 193-384 | 385-1035 | |||||||
Following code snippets show how to create a PDF417 barcode image using Spire.Barcode.
Step 1: Create an instance of BarcodeSetting class.
BarcodeSettings settings = new BarcodeSettings();
Step 2: Set the barode type as Pdf417 and set the data to be encoded.
settings.Type = BarCodeType.Pdf417; settings.Data = "123456789";
Step 3: Set the data mode as numeric.
settings.Pdf417DataMode = Pdf417DataMode.Numeric;
Step 4: Set the error correction level as level 2.
settings.Pdf417ECL = Pdf417ECL.Level2;
Step 5: Initialize an instance of BarcodeGenerator and generate an image based on the settings.
BarCodeGenerator generator = new BarCodeGenerator(settings); Image image = generator.GenerateImage();
Step 6: Save the image in .png format.
image.Save("PDF417Code.png");
Output:

Full Code:
using Spire.Barcode;
using System.Drawing;
namespace PDF417Code
{
class Program
{
static void Main(string[] args)
{
BarcodeSettings settings = new BarcodeSettings();
settings.Type = BarCodeType.Pdf417;
settings.Data = "123456789";
settings.Data2D = "123456789";
settings.Pdf417DataMode = Pdf417DataMode.Numeric;
settings.Pdf417ECL = Pdf417ECL.Level2;
BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();
image.Save("PDF417Code.png");
}
}
}

Generating QR codes with C# is a practical solution for many common development tasks—such as encoding URLs, login tokens, or product information. With the help of a .NET-compatible barcode library, you can quickly create scannable QR images and integrate them into your applications or documents.
This tutorial shows how to build a simple yet powerful C# QR code generator: from generating a QR code from a string, embedding a logo, to inserting the image into PDF, Word, and Excel files. It also covers usage in both Windows and ASP.NET applications, using clean and reusable C# code examples.
Quick Navigation
- 1. How QR Code Generation Works in C#
- 2. Generate QR Code from String in C#
- 3. Insert QR Codes into Documents (PDF, Word, Excel)
- 4. QR Code Generator in Windows and Web Applications
- 5. FAQ
- 6. Conclusion
1. How QR Code Generation Works in C#
Before diving into the code, it’s useful to understand what a QR code is. QR codes are 2D matrix barcodes that can encode URLs, text, contact info, and more. In C#, QR code generation involves three steps:
- Encode your content (usually a string)
- Configure QR code options (error correction, size, margin, etc.)
- Export the result as an image
In this tutorial, we use a simple .NET-compatible library Spire.Barcode for .NET to keep things straightforward and flexible.
Install Spire.Barcode for .NET via NuGet
PM> Install-Package Spire.Barcode
You can also choose Free Spire.Barcode for .NET for smaller tasks:
PM> Install-Package FreeSpire.Barcode
2. Generate QR Code from String in C#
Let’s start with a basic example: generating a QR code from a string in C#. Using the BarcodeSettings and BarCodeGenerator classes provided by Spire.Barcode for .NET, you can easily encode any text or URL into a scannable QR code.
The key steps include:
- Defining QR code content and format using
BarcodeSettings, including data string, error correction level, size, margin, and optional logo; - Generating the image via
BarCodeGenerator, which produces a ready-to-useSystem.Drawing.Imageobject; - Saving or embedding the result in external documents or applications.
The following code demonstrates how to configure the QR code and export it as a PNG image.
using Spire.Barcode;
using System.Drawing;
using System.Drawing.Imaging;
namespace GenerateQRCode
{
class Program
{
static void Main(string[] args)
{
// Initialize barcode settings
BarcodeSettings settings = new BarcodeSettings();
// Specify the barcode type as QR Code
settings.Type = BarCodeType.QRCode;
// Set the QR code data
settings.Data = "https://www.example.com/";
// Set the text to display (optional)
settings.Data2D = "Scan to go to example.com";
settings.ShowTextOnBottom = true;
settings.TextFont = new Font(FontFamily.GenericSansSerif, 16.0f);
// Set data mode and error correction level
settings.QRCodeDataMode = QRCodeDataMode.Auto;
settings.QRCodeECL = QRCodeECL.H;
// (Optional) Embed a logo image in the QR code
settings.QRCodeLogoImage = Image.FromFile("Logo.png");
// Set the width of bar module
settings.X = 3.0f;
// Generate the QR code image
BarCodeGenerator generator = new BarCodeGenerator(settings);
// Generate the QR code image
Image qr = generator.GenerateImage();
// Save the image to a file
qr.Save("QR Code.png", ImageFormat.Png);
}
}
}
You can change the settings.Data to encode any text or URL. To embed a logo, use QRCodeLogoImage with a local image path. Error correction level H ensures that the QR code remains scannable even with a logo.
The QR code generated using C#:

You may also like: How to Scan QR Code Using C#
3. Insert QR Codes into Documents (PDF, Word, Excel)
A common use case for a c# qr generator is embedding QR codes into documents—automatically generating reports, receipts, or certificates. The generated QR image can be inserted into files using standard .NET Office libraries.
Insert into PDF
PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.AppendPage();
page.Canvas.DrawImage(PdfImage.FromImage(qr), 100, 400, 100, 100);
pdf.SaveToFile("output.pdf");
Use cases: digital invoices, shipping labels, authentication docs.
Insert into Word Document
Document doc = new Document();
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();
DocPicture picture = para.AppendPicture(qr);
doc.SaveToFile("output.docx", FileFormat.Docx);
Use cases: contracts, personalized letters, ID cards.
Insert into Excel Worksheet
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
sheet.Pictures.Add(2, 2, qr); // Cell C3
book.SaveToFile("output.xlsx", ExcelVersion.Version2016);
Use cases: customer records, product sheets, logistics tracking.
Recommended article: Read Barcodes from PDF Documents
4. QR Code Generator in Windows and Web Applications
Windows Application
In a Windows Forms app, you can display the generated QR image in a PictureBox, and allow users to save it. This is useful for desktop-based systems like check-in kiosks or internal tools.
pictureBox1.Image = qr;
ASP.NET Web Application
In ASP.NET, return the QR image in a memory stream:
MemoryStream ms = new MemoryStream();
qr.Save(ms, ImageFormat.Png);
return File(ms.ToArray(), "image/png");
These approaches are lightweight and do not depend on heavy frameworks.
FAQ
Q: How to generate a QR code in .NET C# by code? A: Use a barcode library like Spire.Barcode for .NET. Simply define your QR code content, set the desired options (e.g., error correction level, logo image), and export it as an image. It's straightforward to integrate into C# applications.
Q: What is the best QR code generator for C#? A: There are several good options available. Spire.Barcode for .NET is a solid choice—it supports multiple barcode formats, allows logo insertion, and integrates well with Office documents.
Q: Can I adjust the size and layout of the generated QR code? A: Yes. You can modify properties like X, LeftMargin, and TopMargin to control the module size and spacing around the QR code.
Q: How can I use the generated QR code in documents or applications? A: The generated image can be embedded into PDFs, Word documents, Excel sheets, or displayed in Windows Forms or ASP.NET pages. This makes it useful in reports, labels, and web systems.
Conclusion
Creating a QR code generator in C# is simple yet highly effective. This tutorial demonstrated how to generate QR codes with a few lines of C# code, insert them into documents, and deploy them in both desktop and web environments. You can further expand on this by exploring batch generation, QR styling, or integrating scanning features in future enhancements.
To try it yourself, you can apply for a free temporary license here to unlock the full capabilities of Spire.Barcode for .NET.
Code39 is also known as Alpha39, Code 3 of 9, Code 3/9, Type 39, USS Code 39, USD-3. This article will show you how to use Spire.Barcode to create Code39 barcode. It supports 43 characters, consisting of uppercase letters (A through Z), numeric digits (0 through 9) and a number of special characters (*, -, $, /, +, %, and space). Usually Code39 starts and ends with “*”. Here comes to the steps of how to create Code39 barcodes.
Step 1: Create a BarcodeSettings instance.
BarcodeSettings bs = new BarcodeSettings();
Step 2: Set the BarcodeType property to Code39
bs.Type = BarCodeType.Code39;
Step 3: Set the data for the barcode.
bs.Data = "*ABC 12345* ";
Step 4: Generate barcode image using BarCodeGenerator.
BarCodeGenerator bg = new BarCodeGenerator(bs);
bg.GenerateImage().Save("Code39Code.png");
Effective screenshot of Code39 barcode image:

Full codes:
using Spire.Barcode;
namespace Code39
{
class Program
{
static void Main(string[] args)
{
BarcodeSettings bs = new BarcodeSettings();
bs.Type = BarCodeType.Code39;
bs.Data = "*ABC 12345* ";
BarCodeGenerator bg = new BarCodeGenerator(bs);
bg.GenerateImage().Save("Code39Code.png");
System.Diagnostics.Process.Start("Code39Code.png");
}
}
}