Search code examples
c#sql-serverbackup

Get default backup path of sql server programmatically


I am taking backups of certain sql server databases programmatically using c#. I figured that Microsoft.SqlServer.Management.Smo and some other libraries are made for this purpose. Now I can backup a database. Very nice. Here is the code :

var server = new Server(@"" + InstanceName);
var backuper = new Backup();
try
{
    backuper.Action = BackupActionType.Database;
    backuper.Database = DbName;
    backuper.Devices.AddDevice(DbName + ".bak", DeviceType.File);
    backuper.BackupSetName = DbName + " - Yedek";
    backuper.BackupSetDescription = "Açık Bulut Depo - " + DbName + " - Yedek";
    backuper.ExpirationDate = DateTime.Now.AddYears(20);
    server.ConnectionContext.Connect();
    backuper.SqlBackup(server); 
}
catch(Exception ex){//..}

My question here is how can I get the path of the device that the database backed up into? I know I can specify my own path as :

backuper.Devices.AddDevice("C:\SOMEPATH\" + DbName + ".bak", DeviceType.File);

Then I can actually know where it is, but what I want to do is back it up to its default location and get its path. Please help me out with this.


Solution

  • From this blog post, you could use the function below:

    http://www.mssqltips.com/sqlservertip/1966/function-to-return-default-sql-server-backup-folder/

    CREATE FUNCTION dbo.fn_SQLServerBackupDir() 
    RETURNS NVARCHAR(4000) 
     AS 
    BEGIN 
    
     DECLARE @path NVARCHAR(4000) 
    
    EXEC master.dbo.xp_instance_regread 
            N'HKEY_LOCAL_MACHINE', 
            N'Software\Microsoft\MSSQLServer\MSSQLServer',N'BackupDirectory', 
            @path OUTPUT,  
            'no_output' 
    RETURN @path 
    END;