I'm trying to make a backup to a network shared folder with the following code:
string filePath = ("\\pc-usuario\folder\backup\backup.bak")
string connectionString = String.Format(#"Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True", server, database);
using (var connection = new SqlConnection(connectionString))
{
var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", database, filePath);
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.CommandTimeout = 1800;
command.ExecuteNonQuery();
}
}
Got the following error:
The backup device cannot be opened. Operating system error 5(Access denied.).
If I try it with SQLExpress the same error happens. What am I missing?
You havent given the database backup a file name, only a file path
E.g. the final code should read
backup database wibble to disk = '\\pc-usuario\folder\backup\wibble.bak'
Related
Hy I am getting sqlException while trying to backup SQL Server database programatically in ASP.NET core in hosted application. Backup works properly on local maching but after deploying it is throwing SQL exception.
My code is
string fileName = Guid.NewGuid().ToString()+".bak";
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot","DatabaseBackups", fileName);
System.Console.WriteLine(filePath);
string connectionString = configuration.GetConnectionString("DefaultConnection");
var query = $"BACKUP DATABASE MySchool TO DISK='{filePath}'";
using ( SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
var command = new SqlCommand(query, conn);
command.ExecuteNonQuery();
Logger.LogInformation("BackUp Completed");
conn.Close();
}
If its permission issue on the server, I have given full permission to wwwwroot folder in server.
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
I have created a database with this code:
public static void CreateDatabase(string databasePath)
{
AppDomain.CurrentDomain.SetData("DataDirectory", databasePath);
using (var connection = new System.Data.SqlClient.SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=master; Integrated Security=true;;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", "CoolDatabase", databasePath + #"\database.mdf");
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", "CotanDB");
command.ExecuteNonQuery();
}
connection.Close();
}
}
Which creates a nice working .mdf file for my unit tests. However, after running all tests on it, I want to remove it again so it doesn't take up space.
I tried this:
public static void DestroyDatabase(string databasePath)
{
if (File.Exists(databasePath + #"\database.mdf"))
{
File.Delete(databasePath + #"\database.mdf");
}
if (File.Exists(databasePath + #"\database_log.ldf"))
{
File.Delete(databasePath + #"\database_log.ldf");
}
}
But that throws an error
The process cannot access the file 'path to the database\database.mdf'
because it is being used by another process.
So I tried to close all connections to my database so I could drop it and delete the file. However, this does not work:
var server = new Server();
server.KillDatabase(databasePath + #"\database.mdf");
Which throws
Failed to connect to server ..
How do I destroy my local database file?
Edit: I tried the code in the answer in the comments:
using (var connection = new System.Data.SqlClient.SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=master; Integrated Security=true;;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("USE master");
command.ExecuteNonQuery();
command.CommandText =
String.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE", "CotanDB");
command.ExecuteNonQuery();
command.CommandText =
String.Format("DROP DATABASE {0}", "CoolDatabase");
command.ExecuteNonQuery();
}
connection.Close();
}
Followed by the same File.Delete code. But this throws:
User does not have permission to alter database "CoolDatabase", the
database does not exist, or the database is not in a state that allows
access checks.
Figured it out myself. If you call SqlConnection.ClearPool(connection), all connections to your mdf file are dropped, after which you can easily delete it.
Looking back at this, this is a horrible solution and should be avoided, as this construction means your unit tests are now dependent on an external database. Good luck trying to run this in an Azure Pipeline.
If you have the option, use an EntityFramework InMemory database:
https://learn.microsoft.com/en-us/ef/core/providers/in-memory/?tabs=dotnet-core-cli
This question is answered many times in Stackoverflow, But I didn't get proper solution for my project.
Let me show you my code first:
namespace ConsoleDBManagement
{
class Program
{
static void Main(string[] args)
{
//Metioned here your database name
string dbname = "newDb";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=ABC-PC\SQLEXPRESS;database=" + dbname + ";uid=dran;pwd=sri;";
//Enter destination directory where backup file stored
string destdir = "D:\\Working Projects";
//Check that directory already there otherwise create
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("D:\\Working Projects");
}
try
{
//Open connection
sqlcon.Open();
//query to take backup database
//System.IO.File.Create("D:\\Working Projects\\FullBackUp.BAK");
sqlcmd = new SqlCommand("backup database newDb to disk='" + destdir + "\\FullBackUp.BAK'", sqlcon);
sqlcmd.ExecuteNonQuery();
//Close connection
sqlcon.Close();
//Response.Write("Backup database successfully");
}
catch (Exception ex)
{
//Response.Write("Error During backup database!");
}
}
}
}
I am getting exception while query executed.
Cannot open backup device 'D:\Working Projects\FullBackUp.BAK'. Operating system error 3 (The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.
Please give me your suggestions.
When you run backup and/or other external file related commands when using a SQL auth login, the Windows security context is that of the SQL Service.
Your question is duplicate of Backup Permissions. Either grant permission for the SQL Service account/group, or run the backups using a Windows auth login that has permissions to the path.
I have a mssql database on remote machine and backup file for this database. I want to create a method (c#) for restoring of database from backup. I will execute my method on my local machine. Can somebody help me to create such method for restoring remote database?
Try the this:
public void RestoreDatabase(string fileName)
{
try
{
using (SqlConnection conn = new SqlConnection("connectionString"))
{
string sql = "RESTORE DATABASE YourDatabase FROM DISK = N''" + fileName;
conn.Open();
SqlCommand _command = new SqlCommand(sql, conn);
_command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw;
}
}
You call it this way :
RestoreDatabase(#"\\remotemachine\...\YourFile.bak");
NB: Put an actual path for where the file is located