Programmatically Ms Access database backup using C#

QuestionsCategory: C#Programmatically Ms Access database backup using C#
XorientXorient asked 5 months ago

How to take backup of MS Access database using c#.net?

1 Answers
Best Answer
Mahesh DeshmaneMahesh Deshmane answered 5 months ago

Ms Access store everything in one file, like any regular file, so if you want to take backup we just need to copy original MS Access file to a backup folder.

Similar way, if you want to restore the MS Access file from backup folder just need to copy the backup file and store it at the original location (make sure the to change name of file should be same while restoring).
Here is C# code snippet to take Ms Access database backup programmatically :



using System;
using System.IO; 
namespace General
{
    class Program
    {
        static void Main()
        {
            try
            {
                Console.WriteLine("Enter the database full path");
                var currentDatabaseFile = new FileInfo(Console.ReadLine());
                
                if (!File.Exists(currentDatabaseFile.FullName))
                    throw new FileNotFoundException("Invalid database file path");
                
                Console.WriteLine("Enter the directory path to store backup");
                var backupPath = Console.ReadLine();
                
                if (!Directory.Exists(backupPath))
                    throw new DirectoryNotFoundException("Invalid directory path");
                
                var backupName = currentDatabaseFile.Name.Split('.')[0] +
                    DateTime.Now.ToString("ddMMMyyyHHmmss") +
                    currentDatabaseFile.Extension;
                
                var backupFile = backupPath + @"\" + backupName;
                
                File.Copy(currentDatabaseFile.FullName, backupFile, true);
                Console.WriteLine("Taken backup!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
    }
    
}