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

后端 未结 5 1728
感动是毒
感动是毒 2021-02-03 13:35

I\'m trying to write simple application in C# which will allow me to backup, zip and send over ftp my SQL Server database. One problem I have encountered is that I\'m not able t

5条回答
  •  囚心锁ツ
    2021-02-03 14:09

    Ok Guys, Magnus and 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 :). 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. 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!

提交回复
热议问题