locked
Make Sql Backup pragmatically in Asp.Net Core Razor Pages RRS feed

  • Question

  • User-1237764778 posted

    I've been developing an Asp.Net Core Razor Pages for a school,and it's working well.I'd like to add a feature to the app so that authorized users can take backups of the database from time to time,and so they wouldn't need to log into the server to do so.I'd like the c# code I write to create the backup and then let the user choose where they would like to save the .bak file.I wonder if you could help me.The following code I've written doesn't work as it needs access to the server disk,which is not possible.

     public async Task<string> BackupDatabase()
            {
                var sqlConStrBuilder = new SqlConnectionStringBuilder(_connectionString);
                var backupFileName = $@"{_folderPath}\{sqlConStrBuilder.InitialCatalog}({DateTime.Now.Date.ToString("yyyy-MM-dd")}).bak";
                if (!System.IO.Directory.Exists(_folderPath))
                {
                    System.IO.Directory.CreateDirectory(_folderPath);
                }
                using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
                {
                    var query = $"BACKUP DATABASE [{sqlConStrBuilder.InitialCatalog}] TO DISK='{backupFileName}'";
                    using (var command = new SqlCommand(query, connection))
                    {
                        try
                        {
                            await connection.OpenAsync();
                            await command.ExecuteNonQueryAsync();
                            return "Backup done";
                        }
                        catch (Exception ex)
                        {
                            return "Backup encountered a problem" + "\n" + ex.Message;
                        }
                    }
                }

    Saturday, August 3, 2019 6:21 PM

All replies

  • User1724605321 posted

    Hi deh_meisam,

    Did you try to give folder's read/write permissions to app pool identity(AppPool\DefaultAppPool) ?

    Best Regards,

    Nan Yu

    Monday, August 5, 2019 2:35 AM