Search code examples
c#backupsmo

BackupDevice.PhysicalLocation does not add to specified location


Using C# and SMO, when I create backups they are being copied to the default backup location used by SQL Server (C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Backup), instead of the physical location that I specify in code:

 Database database = Server.Databases[dbName]);
  Backup backup = new Backup();

  device = new BackupDevice();
  device.Parent = Server;
  device.Name = dbName + ".bak";
  device.BackupDeviceType = BackupDeviceType.Disk;
  device.PhysicalLocation = Path.Combine(filePath + device.Name); // doesn't appear to do anything
  device.Create();

  backup.Action = BackupActionType.Database;
  backup.Database = database.Name;
  backup.Devices.AddDevice(filePath, DeviceType.File);
  backup.SqlBackup(server);

When I run my code, I find that the path that I specified ("C:\backupTest") is empty and the backup has been added to the default backup location.

Anyone know why this is?


Solution

  • try with below code

    static void BackupDataBase(string databaseName, string destinationPath)
    {
        try
        {
            Server myServer = GetServer();
            Backup backup = new Backup();
            backup.Action = BackupActionType.Database;
            backup.Database = databaseName;
            destinationPath = System.IO.Path.Combine(destinationPath, databaseName + ".bak");
            backup.Devices.Add(new BackupDeviceItem(destinationPath, DeviceType.File));
            backup.Initialize = true;
            backup.Checksum = true;
            backup.ContinueAfterError = true;
            backup.Incremental = false;
            backup.LogTruncation = BackupTruncateLogType.Truncate;
            backup.SqlBackup(myServer);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
    
    private static Server GetServer()
    {
        ServerConnection conn = new ServerConnection("server", "username", "pw");
        Server myServer = new Server(conn);
        return myServer;
    }
    

    refere this codeproject article for more information.