How to create RAR file in c#.net?

QuestionsCategory: C#How to create RAR file in c#.net?
Pooja PatelPooja Patel asked 5 months ago

How to create RAR file in c#.net? To add files and folders into zip file automatically using C# program.

1 Answers
Best Answer
Mahesh DeshmaneMahesh Deshmane answered 4 months ago

To create RAR file in c#.net, we need to install RAR into the machine, without RAR in the machine the code will not work.


using System;
using System.Collections.Generic;
using System.Linq;

namespace RarFiles 
{
 public class Rar 
 {
  static void Main() 
  {
   var rarPackage = "D:/Backup.rar";
   var filesCollection = new List < string > ();
   filesCollection.Add(@ "C:\xx\xxx\xxx\xx.xlsx");
   CreateRarFiles(rarPackage, filesCollection);
  }

  public static bool CreateRarFiles(string rarPackagePath, List < string > collectionFiles)
 {
   try
   {
    var files = collectionFiles.Select(file => "\"" + file).ToList();
    var fileList = string.Join("\" ", files);
    fileList += "\"";
    if (rarPackagePath == null) return false;
    var arguments = $ "A \"{rarPackagePath}\" {fileList} -ep1 -r";
    var processStartInfo = new System.Diagnostics.ProcessStartInfo {
     ErrorDialog = false, 
     UseShellExecute = true,
     Arguments = arguments,
     FileName = @ "C:\Program Files\WinRAR\WinRAR.exe",
     CreateNoWindow = false,
     WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
    };
    var process = System.Diagnostics.Process.Start(processStartInfo);
    process ? .WaitForExit();
    return true;
   }
 catch (Exception)
 {
    return false;
 }
}
}
}

Alternatively, we can also compress files to zip using a readymade library.
System.IO.Compression;


using System.IO;
using System.IO.Compression; 

namespace ZipFiles
{
    public class Zip
    {
        static void Main()
        {
             var archiveFilePath = @"D:\Backup.zip";
            var files = Directory.GetFiles(@"D:\Project");
             using (var archive = ZipFile.Open(archiveFilePath, ZipArchiveMode.Create))                foreach (var fPath in files)
                    archive.CreateEntryFromFile(fPath, Path.GetFileName(fPath));
        }
    }
}