如何使用C#以编程方式获取SQL Server 2008 Express R2的默认备份路径

本文关键字:R2 Express 2008 默认 路径 备份 Server SQL 何使用 编程 获取 | 更新日期: 2023-09-27 18:19:53

我有一个将分发给客户的web应用程序。我将通过管理网页为他们提供备份和恢复后端SQL Server数据库的选项。

对于备份,我只是使用时间戳以编程方式创建一个文件名,并让SQL Server将其保存在默认的备份文件夹中。为了恢复,我想列出备份文件,让用户选择使用哪一个,但我不知道获得文件列表的默认备份文件夹是什么。

如何使用C#以编程方式获取SQL Server 2008 Express R2的默认备份文件夹?

感谢

如何使用C#以编程方式获取SQL Server 2008 Express R2的默认备份路径

要检索给定服务器的备份路径,可以使用SQL server管理对象。Server对象具有名为BackupDirectory的属性。

你会想要这样的东西:

Server srv = new Server("SERVERNAME");
string backUpDir = srv.BackupDirectory;

为此,您需要导入usings/references For:

Microsoft.SqlServer.Management.Smo;
Microsoft.SqlServer.Management.Common;

您将在此处找到有关如何与SQL Server管理对象交互的详细信息。

尝试采用这个存根:

    private void GetSqlDefaultInfo(string InstanceName, string ServerName)
    {
        try
        {
            InstanceName = string.IsNullOrEmpty(InstanceName) ? "MSSQLSERVER" : InstanceName;
            if (string.IsNullOrEmpty(ServerName))
                ServerName = Environment.MachineName;
            using (var registryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ServerName))
            {
                object sqlInstance;
                using (var subKey = registryKey.OpenSubKey(@"SOFTWARE'Microsoft'Microsoft SQL Server'Instance Names'SQL"))
                    sqlInstance = subKey.GetValue(InstanceName);
                if (sqlInstance != null && !string.IsNullOrEmpty(sqlInstance.ToString()))
                {
                    var sqlPathKey = string.Format(@"SOFTWARE'Microsoft'Microsoft SQL Server'{0}'MSSQLServer",
                                                   sqlInstance);
                    object defaultData, defaultLog, backupDirectory, sqlPath;
                    using (var subKey = registryKey.OpenSubKey(sqlPathKey))
                    {
                        defaultData = subKey.GetValue("DefaultData");
                        defaultLog = subKey.GetValue("DefaultLog");
                        backupDirectory = subKey.GetValue("BackupDirectory");
                    }
                    sqlPathKey = string.Format(@"SOFTWARE'Microsoft'Microsoft SQL Server'{0}'Setup", sqlInstance);
                    using (var subKey = registryKey.OpenSubKey(sqlPathKey))
                        sqlPath = subKey.GetValue("SQLDataRoot");
                    DataFilePath = defaultData != null
                                       ? defaultData.ToString()
                                       : Path.Combine(sqlPath.ToString(), "Data").TrimEnd('''');
                    LogFilePath = defaultLog != null
                                      ? defaultLog.ToString()
                                      : Path.Combine(sqlPath.ToString(), "Data").TrimEnd('''');
                    FTSIndexFilePath = DataFilePath;
                    ContentFilePath = DataFilePath;
                    BackupFilePath = backupDirectory != null
                                         ? backupDirectory.ToString()
                                         : Path.Combine(sqlPath.ToString(), "Backup").TrimEnd('''');
                }
            }
        } catch(Exception)
        {
        }
    }

下面的查询应该为您提供每个数据库的物理设备名称(或路径)。您可以根据自己的需求进行定制:

select
    database_name,
    backup_type,
    physical_device_name -- path
from
(
    select 
        row_number() over (partition by database_name,type order by backup_start_date desc) as rownum,
        database_name,
        case type 
            when 'L' then 'Log' 
            when 'D' then 'Data'
            else '??? '+type 
        end as backup_type,
        physical_device_name
    from msdb.dbo.backupset a 
    join msdb..backupmediaset b on a.media_set_id = b.media_set_id 
    join msdb.dbo.backupmediafamily c on a.media_set_id = c.media_set_id
) x
where rownum=1
order by database_name asc, backup_type

我最终使用了以下SqlCommand。。。这个解决方案出现在另一个答案中,但由于某种原因被删除了。?不管怎样,这是我最终使用的命令:

EXEC  master.dbo.xp_instance_regread  N'HKEY_LOCAL_MACHINE', N'Software''Microsoft''MSSQLServer''MSSQLServer',N'BackupDirectory'

这是我的C#代码中的命令,它显示了存储在变量backupFolder:中的默认备份文件夹路径

            SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            SqlDataReader reader;
            cmd.CommandText = "EXEC  master.dbo.xp_instance_regread  N'HKEY_LOCAL_MACHINE', N'Software''Microsoft''MSSQLServer''MSSQLServer',N'BackupDirectory'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = myConnection;
            myConnection.Open();
            SqlDataReader myDataReader = cmd.ExecuteReader();
            myDataReader.Read();
            string backupFolder = myDataReader.GetString(1);

您要查找的值存储在注册表中

Key: HKEY_LOCAL_MACHINE'SOFTWARE'Microsoft'Microsoft SQL Server'MSSQL.2'MSSQLServer
Value: BackupDirectory

请注意,密钥取决于您的SQL Server实例名称。

declare @regread nvarchar(max)
select  top 1 @regread = substring(registry_key,6,len(registry_key)-16)
from    sys.dm_server_registry
where   registry_key like '%Parameters'
group by registry_key
select @regread = 'exec master..xp_regread ''HKEY_LOCAL_MACHINE'','''+@regread+''', ''BackupDirectory'''
exec sp_executesql @regread