1

我在谷歌搜索后使用引用编写了这段代码,但是在执行BackupDatabase(myfilename.bak)它时,我在第 1 行出现错误。11并说:

FileNotFoundException 未处理

Could not load file or assembly 'Microsoft.SqlServer.SmoEnum, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

我已经检查过该SMO文件是否存在于我的驱动器中,bin也存在于其中。我无法理解这个问题。请帮忙。

public readonly string ConnectionString = MyApp.Properties.Settings.Default.DbConnectionString;
public void BackupDatabase(string backUpFile)
    {
        ServerConnection con = new ServerConnection(ConnectionString);
        Server server = new Server(con);
        Backup source = new Backup();
        source.Action = BackupActionType.Database;
        source.Database = "TestDB";
        BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
        source.Devices.Add(destination);
        source.SqlBackup(server);
        con.Disconnect();
    }

另外,我试着做:

if(con.Isopen)
{
    //Then all of my code goes in here
}

但是这个条件永远不会满足,内部代码永远不会被执行。

我还观察到,就像我们以前做con.open()的那样Database Connection,我们没有这样的选项ServerConnection

编辑-1:

在调试时我发现了这个con

在此处输入图像描述

编辑-2:

我对这个问题有另一个查询:DB的connectionString是否与ServerConnection的连接字符串相同???

我实际上是在谈论这条线:-

public readonly string ConnectionString = MyApp.Properties.Settings.Default.DbConnectionString;

因为上面ConnectionString包含{server='Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDb.mdf;Integrated Security=True;User Instance=True';Trusted_Connection=true;multipleactiveresultsets=false}

4

1 回答 1

0

要创建 Smo 连接,您只需要一个 ServerConnection,而要创建一个 ServerConnection,您只需要 SQL Server 的名称。例子

ServerConnection serverConnection = new ServerConnection("mySQLServer")
Smo.Server smoServer = new Smo.Server(serverConnection)

如我所见,您正在使用 SQLExpress。然后您的 SQL Server 实例将默认称为“.\SQLEXPRESS”,因此您必须执行以下操作:

ServerConnection serverConnection = new ServerConnection(".\\SQLEXPRESS")
Smo.Server smoServer = new Smo.Server(serverConnection)

注意 '\' 以防止在字符串中转义。

如果有帮助,请查看我的工作示例: https ://stackoverflow.com/a/23096791/2948212

于 2014-04-16T00:34:00.433 回答