Thursday, 22 February 2018

How to delete files from directory using c# MVC

Description : In this article how to remove multiple files remove from 1 single directory using foreach loop in MVC using c#

string FilePath = HttpContext.Server.MapPath("~/YourMainDirectoryName/");

// First check if directory exists or not
if (!Directory.Exists(FilePath))
{
 string[] files = Directory.GetFiles(FilePath);

 if (files.Length > 0)
 {
  foreach (string filePaths in files)
                      System.IO.File.Delete(filePaths);
 }
}

// at the end of loop if you want to delete main directory write below line
Directory.Delete(FileSavePath);

// again if you want to create same blank directory write below line
Directory.CreateDirectory(FileSavePath);

How to generate random 10 digit number using sql

Description : In this post how to create 10 digits random number from sql select query, use this type query in generate Order Number or Client Unique number

SELECT RIGHT('000000' + CAST(ABS(CHECKSUM(NEWID())) % 9999999999 AS varchar(10)), 10)

Result : 0027125182

How to mearge multiple PDF files with page number using PDFSharp using C# MVC

Description : In this article how to mearge multiple PDF file using PDFSharp dll in c# MVC

Step 1 : first install this package from nuget "Install-Package PdfSharp -Version 1.32.3057"

string DirectoryPath = HttpContext.Server.MapPath("~/YourDirectoryName/");

// Get all PDF Files
string[] pdfs = Directory.GetFiles(DirectoryPath);

// Pass all PDF files in function
MergeMultiplePDFIntoSinglePDF(DirectoryPath + "YourMeargeFileName.pdf", pdfs);

// Add below function for generate single pdf file
private void MergeMultiplePDFIntoSinglePDF(string outputFilePath, string[] pdfFiles)
{
 PdfDocument document = new PdfDocument();

 foreach (string pdfFile in pdfFiles)
 {
  PdfDocument inputPDFDocument =

  PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);



  document.Version = inputPDFDocument.Version;

  foreach (PdfPage page in inputPDFDocument.Pages)
  {
     document.AddPage(page);
  }
 }

 XFont font = new XFont("Verdana", 9);
 XBrush brush = XBrushes.Black;

 string noPages = document.Pages.Count.ToString();

 for (int i = 0; i < document.Pages.Count; ++i)
 {
  PdfPage page = document.Pages[i];

  // Make a layout rectangle.
  XRect layoutRectangle = new

  XRect(240/*X*/, page.Height - font.Height - 10/*Y*/

  , page.Width/*Width*/, font.Height/*Height*/);

  using (XGraphics gfx = XGraphics.FromPdfPage(page))
  {
     gfx.DrawString("Page " + (i + 1).ToString() + " of " +

     noPages, font, brush, layoutRectangle, XStringFormats.Center);
  }
 }

 document.Options.CompressContentStreams = true;
 document.Options.NoCompression = false;
 document.Save(outputFilePath);
}