Archive for the ‘c#’ Category

Return pdf to browser in a C# razor page using itext7

leave a comment »

Sample code to return a PDF file to the browser in a Razor c# page using itext7.

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using System.IO;

public IActionResult OnPostManipulatePdf(String dest)
    MemoryStream ms = new MemoryStream();

    PdfWriter writer = new PdfWriter(ms);
    PdfDocument pdfDoc = new PdfDocument(writer);
    Document doc = new Document(pdfDoc);

    Paragraph header = new Paragraph("header");


    byte[] byteInfo = ms.ToArray();
    ms.Write(byteInfo, 0, byteInfo.Length);
    ms.Position = 0;

    FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");

    //Uncomment this to return the file as a download
    //fileStreamResult.FileDownloadName = "Output.pdf";

    return fileStreamResult;


Written by M Kapoor

September 23, 2020 at 2:49 pm

Posted in c#, Programming

Tagged with , , ,

Split an Excel file’s tabs into CSV with C#

leave a comment »

Split an Excel file into csv, with each tab going into a separate csv file, in the background using C#.

using System.IO;
using Microsoft.Office.Interop.Excel;

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

//Run in background
app.DisplayAlerts = false;

//Open excel file
Workbook wb = app.Workbooks.Open("path_to_excel.xls");

//Iterate through sheets in the excel file
foreach (Worksheet sheet in wb.Worksheets)
    string sheetName = sheet.Name;
    //Output file name
    string outputFilepath = sheetName + ".csv";
    //Save the sheet as CSV
    sheet.SaveAs(outputFilepath, XlFileFormat.xlCSVWindows);


Written by M Kapoor

December 24, 2019 at 3:19 am

Posted in c#, Programming

Tagged with ,

Validating a XML against XSD schema in C#

leave a comment »


xmlFileName: Input XML file name
schemaFileName: Input XSD file name


results: Results output

using System.Xml;
using System.Xml.Schema;
using System.IO;

static List<string> results = new List<string>();

        static void Validate(string xmlFileName, string schemaFileName)
            XmlDocument x = new XmlDocument();
            string source = xmlFileName;

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CloseInput = true;
            settings.ValidationEventHandler += Handler;

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, schemaFileName);
            settings.ValidationFlags =
                 XmlSchemaValidationFlags.ReportValidationWarnings |
            XmlSchemaValidationFlags.ProcessIdentityConstraints |
            XmlSchemaValidationFlags.ProcessInlineSchema |

            StringReader r;
            using (StreamReader sr = new StreamReader(source))
                r = new StringReader(sr.ReadToEnd());

            using (XmlReader validatingReader = XmlReader.Create(r, settings))
                while (validatingReader.Read()) { /* just loop through document */ }

        private static void Handler(object sender, ValidationEventArgs e)
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
                results.Add(String.Format("Line: {0}, Position: {1} "{2}"", e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));

Written by M Kapoor

September 30, 2014 at 3:21 pm

Posted in c#

C#: Recursively getting a list of files with a specific extension

leave a comment »

How to recursively get a list of files with a specific extension in C#.


sDir – Starting directory
SExtension – file extension to filter by
List files – A empty list that is used to keep found files while recursing.

        public List<string> getFiles(string sDir, string sExtension, List<string> files)
            foreach (string d in Directory.GetDirectories(sDir))
                foreach (string f in Directory.GetFiles(d))
                    if (f.EndsWith(sExtension))
                getFiles(d, sExtension, files);
            return files;

Starting Source:

Written by M Kapoor

September 22, 2014 at 3:28 pm

Posted in c#