简体   繁体   English

使用c#创建SQL Server备份文件(.bak)到任何位置

[英]Creating SQL Server backup file (.bak) with c# to any location

I'm trying to write simple application in C# which will allow me to backup, zip and send over ftp my SQL Server database. 我正在尝试用C#编写简单的应用程序,这将允许我备份,压缩和通过ftp发送我的SQL Server数据库。 One problem I have encountered is that I'm not able to create the backup file (.bak) if I try to do it in different location than "C:\\Program Files\\Microsoft SQL Server\\MSSQL.3\\MSSQL\\Backup" or "C:\\Program Files\\Microsoft SQL Server\\MSSQL.3\\MSSQL\\Data" folder. 我遇到的一个问题是,如果我尝试在“C:\\ Program Files \\ Microsoft SQL Server \\ MSSQL.3 \\ MSSQL \\ Backup”之外的其他位置执行此操作,则无法创建备份文件(.bak)或“C:\\ Program Files \\ Microsoft SQL Server \\ MSSQL.3 \\ MSSQL \\ Data”文件夹。 I understand that this is a premission problem. 我知道这是一个暂缓问题。 Could someone point me to the resources or write here a short snippet how to programmatically add such a permission to any folder on my system. 有人可以指向我的资源或在这里写一个简短的片段如何以编程方式将这样的权限添加到我的系统上的任何文件夹。

Regards Kris 关心克里斯

i assume you are running your programm as a scheduled task ... did you give writing permissions to the target folder for the executing user of the task?? 我假设您正在运行您的程序作为计划任务...您是否为任务的执行用户提供了目标文件夹的写入权限?

edit: 编辑:
with permissions you can have 2 scenarios: 有权限,你可以有2个场景:

  • windows authenification Windows身份验证
  • mixed authentification 混合认证

if you are using windows authentification, the read and write permissions of the windows user are taken. 如果您使用的是Windows身份验证,则会获取Windows用户的读写权限。 otherwise the permissions for the sql server service account. 否则为sql server服务帐户的权限。

and this behaviour makes sense to me and maybe hits the nail in your scenario! 这种行为对我来说很有意义,也许在你的场景中可能会受到影响!

edit 2: 编辑2:
i don't want to encourage you to do so ... some admins may hate you when you mess up their acl's but this may do the trick 我不想鼓励你这样做......一些管理员可能会恨你,当你搞砸了他的ACL的,但是可能做的伎俩

btw: Magnus Johansson already gave you a "try-this" link 顺便说一句:Magnus Johansson 已经给你一个“试试这个”链接

no matter for which method you go - be sure to hand in the correct user (as descriped above!) 无论你采用哪种方法 - 一定要交给正确的用户(如上所述!)

(for full history) (完整历史)
... ...
side-note: 边注:
i know this is not the exact answer to your question, but i would recommend you smo to generate backups ... 我知道这不是你问题的确切答案,但我建议你smo生成备份......

like 喜欢

using Microsoft.SqlServer.Management.Smo;

var bdi = new BackupDeviceItem(/* your path inlcuding desired file */);
var backup = new Backup
{
    Database = /* name of the database */,
    Initialize = true
};

backup.Devices.Add(bdi);

var server = new Server(this.SqlServer);

try
{
    backup.SqlBackup(server);
}
catch (Exception ex)
{
    // * log or sth
}

you only have to care for the .dll's. 你只需要关心.dll的。 take assemblies for the desired server version (some params/properties vary through different server versions) 获取所需服务器版本的程序集(某些参数/属性因服务器版本而异)
more info here 更多信息在这里

Ok Guys, Magnus and dittodhole! 好伙计们,马格努斯和dittodhole! Thanks a lot for your help. 非常感谢你的帮助。 I have combined Magnus'es link to the article on setting up permisions on the folder together with some more research and finally I've got it :). 我将Magnus'es链接到关于在文件夹上设置permisions的文章以及一些更多的研究,最后我得到了它:)。 So reassuming, I'm using Smo, and to create a folder with proper permissions I have to look for the group instead of win32_Users. 所以重新说,我正在使用Smo,并创建一个具有适当权限的文件夹,我必须寻找组而不是win32_Users。 Here you go a short snippet if someone finds this post he can find it usefull: 如果有人发现这篇帖子他会发现它很有用,你可以在这里找一个简短的片段:

string tempPath = Directory.CreateDirectory("C:\\path_to_your_folder").FullName;

//set permissions
SelectQuery sQuery = new SelectQuery("Win32_Group", 
                                     "Domain='" + 
                                     System.Environment.UserDomainName.ToString() + 
                                     "'");
try
{
    DirectoryInfo myDirectoryInfo = new DirectoryInfo("C:\\path_to_your_folder");
    DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
    ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
    foreach (ManagementObject mObject in mSearcher.Get())
    {
        string User = System.Environment.UserDomainName + "\\" + mObject["Name"];
        if(User.StartsWith("your-machine-name\\SQL"))
        {
            myDirectorySecurity.
            AddAccessRule(new FileSystemAccessRule(User, 
                                                   FileSystemRights.FullControl,
                                                   AccessControlType.Allow));
        }
    }
    myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
catch (Exception ex)
{
    Console.WriteLine(ex.StackTrace);
}

Again thanks everyone for your help! 再次感谢大家的帮助! Stackoverflow rocks! Stackoverflow岩石!

Here is a procedure is use for back up in C#.Hope it helps 这是一个用于在C#备份的过程。希望它有所帮助

   public void BackupDatabase (string BackUpLocation, string BackUpFileName, string 
   DatabaseName, string ServerName )
   {

        DatabaseName = "[" + DatabaseName + "]";

        string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;

        BackUpFileName = BackUpFileName + fileUNQ + ".bak";
        string SQLBackUp = @"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + @"\" + BackUpFileName + @"'";

        string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";

        SqlConnection cnBk = new SqlConnection(svr);
        SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);

        try
        {
            cnBk.Open();
            cmdBkUp.ExecuteNonQuery();
            Label1.Text = "Done";
            Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
        }

        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
            Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
        }

        finally
        {
            if (cnBk.State == ConnectionState.Open)
            {

                cnBk .Close(); 
            } 
      } 
    }

Take a look at this article . 看看这篇文章

Remember to set the permissions for the account that the SQL Server instance is running with. 请记住为运行SQL Server实例的帐户设置权限。

Although this may not answer your immediate question, I'd advice you to look into SQL Server Integration Services (SSIS). 虽然这可能无法回答您的直接问题,但我建议您研究SQL Server Integration Services(SSIS)。 This looks like the exact thing SSIS was created for, and in the 2008 version there's the possibility to use C# code if needed, should the standard components not do what you need (earlier versions used VB.NET). 这看起来就像SSIS的创建一样,在2008版本中,如果需要,可以使用C#代码,如果标准组件不能满足您的需求(早期版本使用VB.NET)。

MSDN SSIS Info Link 1 MSDN SSIS信息链接1
SSIS 2005 Tutorial Link 2 SSIS 2005教程链接2

Take a look at it. 看看吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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