While developing applications for E-commerce or other apps, you may need to add the functionality to generate QR code in your C# ASP.NET application, so in this article, I am going to explain about how you can generate QR code in C# using ZXing.net library with ASP.NET MVC web-application sample project. I have also explained the way to decode (read) plain text from QR image using the same ZXing library.So, let's get started with it.

Step 1: Create a new project in Visual Sutdio for QR code generator in C#, MVC

Create a new project in your Visual Studio, by navigating to "File"-> "New"-> "Project".

Select "Web" in the left pane and "ASP.NET Web application" in the right pane, provide a name for your web application(In my example it's "QRCodegenerator"), Click "OK".

Now Select MVC template to generate basic HomeController and other details, as shown below

qr-code-generator-step-2-min.png

Step 2:  Install the ZXing.Net Nuget Package

 Install the ZXing.NET in your project using Nuget package manager, for this navigate to "Tools"-> "Nuget Package Manager" -> "Manage NuGet package for the solution...", then switch to "browse" tab and search for "ZXing.NET"

zxing-net-qr-code-generator-csharp-dot-net-min.png

after hangfire is installed successfully, you need to create a Model for QR Code generator.

Step 3: QR Code generator Model

Right-click on your projects "Model" folder and then create new class Model "QRCodeModel.cs" and the code below will be 

public class QRCodeModel
    {
        [Display(Name = "QRCode Text")]
        public string QRCodeText { get; set; }
        [Display(Name = "QRCode Image")]
        public string QRCodeImagePath { get; set; }
    }

Step 4: Create a new controller

Now, let's create a new controller in your controller's folder, right-click on your controller's folder , select "Add"->"Controller"->"MVC 5 Empty controller"-> Provide name "QRCodeGenerator" and click "OK"

In your Controller, we need to add the C# code to generate QR code using ZXing.NET

 [HttpPost]
        public ActionResult Generate(QRCodeModel qrcode)
        {
            try
            {
                qrcode.QRCodeImagePath = GenerateQRCode(qrcode.QRCodeText);
                ViewBag.Message = "QR Code Created successfully";
            }
            catch (Exception ex)
            {
                //catch exception if there is any
            }
            return View("Index",qrcode);
        }

        private string GenerateQRCode(string qrcodeText)
        {
            string folderPath = "~/Images/";
            string imagePath = "~/Images/QrCode.jpg";
            // If the directory doesn't exist then create it.
            if (!Directory.Exists(Server.MapPath(folderPath)))
            {
                Directory.CreateDirectory(Server.MapPath(folderPath));
            }

            var barcodeWriter = new BarcodeWriter();
            barcodeWriter.Format = BarcodeFormat.QR_CODE;
            var result = barcodeWriter.Write(qrcodeText);

            string barcodePath = Server.MapPath(imagePath);
            var barcodeBitmap = new Bitmap(result);
            using (MemoryStream memory = new MemoryStream())
            {
                using (FileStream fs = new FileStream(barcodePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    barcodeBitmap.Save(memory, ImageFormat.Jpeg);
                    byte[] bytes = memory.ToArray();
                    fs.Write(bytes, 0, bytes.Length);
                }
            }
            return imagePath;
        }

As you can see in the above code, in the GenerateQRCode ActionMethod, we are passing a string, which is then converted into an image and then the resulted image is copied into our custom path "~/Images/QrCode.jpg"

 var barcodeWriter = new BarcodeWriter();
            barcodeWriter.Format = BarcodeFormat.QR_CODE;
            var result = barcodeWriter.Write(qrcodeText);

            string barcodePath = Server.MapPath(imagePath);
            var barcodeBitmap = new Bitmap(result);
            using (MemoryStream memory = new MemoryStream())
            {
                using (FileStream fs = new FileStream(barcodePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    barcodeBitmap.Save(memory, ImageFormat.Jpeg);
                    byte[] bytes = memory.ToArray();
                    fs.Write(bytes, 0, bytes.Length);
                }
            }

Next step is to generate Code in Index.cshtml view, right-click the Index ActionMethod and add the below code

@model QRCodeGenerator.Models.QRCodeModel

@{
    ViewBag.Title = "Generate QR COde";
}

<h2>Generate QRCode</h2>


@using (Html.BeginForm("Generate", "QRCodeGenerator", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <span style="color:red; ">@ViewBag.Message </span>
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.QRCodeText, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.QRCodeText,  new { @class = "form-control"  })
                @Html.ValidationMessageFor(model => model.QRCodeText, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.QRCodeImagePath, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @if (Model != null && !String.IsNullOrEmpty(Model.QRCodeImagePath))
                {
                    <img src="@Url.Content(Model.QRCodeImagePath)" alt="Image" />
                }

            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Generate QR" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Read QR Code", "Read")
</div>

@section scripts{
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

}

In the above view, we have just created the form, which will submit string from which we want to generate QR code, and when QR code image is generated, we will show it in the view.

Note: we have scripts section in _layout.cshtml and we are adding some js files in it using @section

Step 5: Code to convert QR Image to Plain text (decoding QR code to string)

Go to your QRCodeGeneratorController again and add the below C# code

public ActionResult Read()
        {
            return View(ReadQRCode());
        }

        private QRCodeModel ReadQRCode()
        {
            QRCodeModel barcodeModel = new QRCodeModel();
            string barcodeText = "";
            string imagePath = "~/Images/QrCode.jpg";
            string barcodePath = Server.MapPath(imagePath);
            var barcodeReader = new BarcodeReader();

            var result = barcodeReader.Decode(new Bitmap(barcodePath));
            if (result != null)
            {
                barcodeText = result.Text;
            }
            return new QRCodeModel() { QRCodeText = barcodeText, QRCodeImagePath = imagePath };
        }

in the above ReadQRCode ActionMethod, we are using the Image from our pre-defined image path (~/Images/QrCode.jpg) and using the ZXing.Net .Decode function to convert the bitmap image into the string

var barcodeReader = new BarcodeReader();

            var result = barcodeReader.Decode(new Bitmap(barcodePath));
            if (result != null)
            {
                barcodeText = result.Text;
            }

which we are returning back in the Read View using QRCodeModel.cs 

In Read.cshtml , your code to show plain-text and image will be as below

@model QRCodeGenerator.Models.QRCodeModel
@{
    ViewBag.Title = "Read";
}

<h2>Read</h2>


<div class="form-horizontal">

  
    <div class="form-group">
       <label class="control-label col-md-2"> Decoded Text from Model</label>
        <div class="col-md-10">
            @Html.DisplayFor(model => model.QRCodeText, new {  @class = "form-control"  })
            @Html.ValidationMessageFor(model => model.QRCodeText, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2"> QR image</label>
        <div class="col-md-10">
            @if (Model != null && !String.IsNullOrEmpty(Model.QRCodeImagePath))
        {
            <img src="@Url.Content(Model.QRCodeImagePath)" alt="Image" />
    }

        </div>
    </div>

    
</div>

Step 6: Build and run your project 

We are done with our coding part, let's build the project and run it in web-browser.

You will see the output as below

qr-code-generator-asp-net-min.png

entering text and clicking "Generate QR" will help you generate QR code as shown in below image

qa-code-generator-c-sharp-min.png

Clicking the "Read QR Code" link, you will see output as below

decode-qr-code-in-asp-net-min.png

Complete working demo .gif file is here

qr-code-generator-in-c-sharp-asp-net-mvc-min.gif

Alternative way (QR generation in Razor View using helper method)

You can also Create Helper method also and just directly generate QR in the View using the below Helper method

using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZXing;
using ZXing.Common;

namespace QRCodeGenerator.Models
{
    public static class QRHelper
    {
        public static IHtmlString GenerateQRCode(this HtmlHelper html, string url, string alt = "GeneratedQRCode", int height = 200, int width = 200, int margin = 0)
        {
            var qrWriter = new BarcodeWriter();
            qrWriter.Format = BarcodeFormat.QR_CODE;
            qrWriter.Options = new EncodingOptions() { Height = height, Width = width, Margin = margin };

            using (var q = qrWriter.Write(url))
            {
                using (var ms = new MemoryStream())
                {
                    q.Save(ms, ImageFormat.Png);
                    var img = new TagBuilder("img");
                    img.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
                    img.Attributes.Add("alt", alt);
                    return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
                }
            }
        }
    }
}

In your View, refer the method with @using Namespace and add the HTML helper with string as below

@using QRCodeGenerator.Models


@Html.GenerateQRCode("QA WIth Experts")

Output:

qr-code-generation-using-razor-view-and-helper-method-min.png

that's it, we are done, feel free to ask questions or let us know your thoughts on this using comments section.

You may also like to read:

Barcode generator in C# ( and how to read barcode )

Read or generate QR Code in ASP.NET Core

Read or Generate QR Code using Javascript

Create Captcha in asp.net with refresh button (Code with example)

Best C# programming course available online (Free OR paid)