C# 数据库不存在错误

C# 数据库不存在错误,c#,sql-server,C#,Sql Server,当我进行数据库备份时,我会得到一个错误,即数据库不存在,但我可以很好地附加数据库,其他过程(如数据插入和更新)也可以很好地工作。但是,当我进行数据库备份时,会出现以下错误 我显示错误屏幕截图和备份按钮代码 string cnstr="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\fees_data.mdf;Integrated Security=True;User Instance=True;" SqlConnectio

当我进行数据库备份时,我会得到一个错误,即数据库不存在,但我可以很好地附加数据库,其他过程(如数据插入和更新)也可以很好地工作。但是,当我进行数据库备份时,会出现以下错误

我显示错误屏幕截图和备份按钮代码

string cnstr="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\fees_data.mdf;Integrated Security=True;User Instance=True;"



SqlConnection connect;
        connect = new SqlConnection(cnstr);
        connect.Open();
        if (txtdname.Text == "")
        { dname = "Default.bak"; }
        else
        { dname = txtdname.Text + ".bak"; }
        SqlCommand command;
        command = new SqlCommand(@"backup database fees_data to disk ='c:\DATABackup\" + dname + "'", connect);
        command.ExecuteNonQuery();
        connect.Close();
单击“备份”按钮时,会出现以下错误:

“数据库'fees_data'不存在。请确保输入的名称正确。 备份数据库正在异常终止。“


数据库名称可能与.mdf文件名不同

运行此查询时会得到什么结果

select name from sys.databases;
请在此处使用正确的名称。

而不是此代码

SqlCommand command;
   command = new SqlCommand(@"backup database fees_data to disk ='c:\DATABackup\" + dname + "'", connect);
   command.ExecuteNonQuery();
使用下面编写的代码

string fullPath= "";
 string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
 fullPath= (System.IO.Path.GetDirectoryName(executable));
 AppDomain.CurrentDomain.SetData("DataDirectory", fullPath);
 fullPath=fullPath+"\\fees_data.mdf";

 SqlCommand command;
 command = new SqlCommand(@"backup ['"+fullPath+"'] to disk ='c:\DATABackup\" + dname + "'", connect);
 command.ExecuteNonQuery();

这将在这个工作,你只是符合数据库名称和路径没有任何代码错误只是检查你的数据库名称和路径,你存储备份文件。。。