简体   繁体   中英

Access Database Backup using C#

Hi I created a wpf application in C# using Access as the db. I am trying to create a backup where the user will click on the backup button and then the file explorer window will open so that the user can choose where they want to save their backup. I looked on the site and there are several topics on this but I did not see one where the file explorer was called. I know how to create a backup copy using the following:

     private void BackupDatabase_Click(object sender, RoutedEventArgs e)
    {
        File.Copy("Results_West.mdb", "Results_WestBak.mdb", true);
    }

The above works and saves the backup where the executable is located but I'm not sure how to call windows file explorer and then do the save where the user wants to like when you're saving other files. Any ideas on this would be helpful. Thanks.

You should use a SaveFileDialog located under the Microsoft.Win32 namespace.

The SaveFileDialog doesn't actually do any saving work, it's just a dialog to help you get a destination file path.

SaveFileDialog.ShowDialog() will show the dialog, and when the user closes the dialog (eg. by accepting or declining), it will return a nullable boolean value to indicate if the dialog was accepted, declined or cancelled.

If ShowDialog() returns true, you should have a file path (string) that you can use in your copy method.

I hope this helps you understand. I have attached some code to help.

public void BackupDatabase()
{
    // The relative or full path of the database that you want to copy
    string fileToBackup = "Results_West.mdb";

    // The directory the save file dialog opens by default
    // --- Optional ---
    string initialFilePath = @"C:\Backup";

    // Initialize the sfd
    SaveFileDialog sfd = new SaveFileDialog
    {
        Title = "Choose a destination for your backup.",
        Filter = "Microsoft Access File|*.mdb",
        // --- Optional ---
        InitialDirectory = initialFilePath,
    };

    // sfd.ShowDialog() returns a nullable bool
    // If it returns true, you should have enough information to work with.
    // We need to escape if the result is not true.
    if (sfd.ShowDialog() != true)
    {
        return;
    }

    try
    {
        // sfd.FileName is the full path that the user selected.
        // 3rd parameter (true) specifies overwrite
        File.Copy(fileToBackup, sfd.FileName, true);
    }
    catch
    {
        // Failed to copy file.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM