Mahmood Jenami
Mahmood Jenami

Reputation: 431

Invalid database name specified for backup or restore operation in when database path is long

I have a db with a long path:

C:\\Users\\UserName\\AppData\\Local\\Apps\\2.0\\ZV0DG5JM.3OH\\XQ31WEZB.OKA\\camman.exe_af50f6b9afda55f2_0001.0005_none_2c544a12b9bb2c09\\CameraManDB.mdf

I use the following code to backup:

public void BackupDatabase(string filePath, string DbPath)
{
    using (CameraManDBEntities dbEntities = new CameraManDBEntities())
    {
        string backupQuery = @"BACKUP DATABASE @DbPath TO DISK = N'{0}'";
        backupQuery = string.Format(backupQuery, filePath);

        dbEntities.Database.SqlQuery<object>(backupQuery, new SqlParameter("DbPath", DbPath)).ToList().FirstOrDefault();
    }
}

When I call the following method:

BackupDatabase(BackUpFileName, @"C:\Users\Mahmood\AppData\Local\Apps\2.0\ZV0DG5JM.3OH\XQ31WEZB.OKA\camman.exe_af50f6b9afda55f2_0001.0005_none_2c544a12b9bb2c09" + "\\CameraManDB.mdf");

it throws this exception:

Invalid database name 'C:\Users\Mahmood\AppData\Local\Apps\2.0\ZV0DG5JM.3OH\XQ31WEZB.OKA\camman.exe_af50f6b9afda55f2_0001.0005_none_2c544a12b9bb2c09\CameraManDB.mdf' specified for backup or restore operation.\r\nBACKUP DATABASE is terminating abnormally.

I think it's very simple but I couldn't find any obvious solution about long identifiers.

Thank you for guiding!

Upvotes: 0

Views: 584

Answers (1)

Rhumborl
Rhumborl

Reputation: 16609

You are getting the error because you are passing the physical path of the database in parameter @DbPath but then using that parameter at the place in BACKUP where you specify the database name. This database obviously doesn't exist, hence the error.

You need to change it as follows:

public void BackupDatabase(string filePath, string dbName)
{
    using (CameraManDBEntities dbEntities = new CameraManDBEntities())
    {
        string backupQuery = @"BACKUP DATABASE @DbName TO DISK = N'{0}'";
        backupQuery = string.Format(backupQuery, filePath);

        dbEntities.Database.SqlQuery<object>(backupQuery,
            new SqlParameter("DbName", dbName)).ToList().FirstOrDefault();
    }
}

BackupDatabase(BackUpFileName, "CameraManDB");

I would also make the path a parameter instead of doing dynamic SQL, i.e.:

BACKUP DATABASE @DbName TO DISK = @FilePath

Upvotes: 1

Related Questions