Skip to main content
 首页 » 编程设计

c#之无法将 C# 可执行文件连接到远程计算机上的数据库文件

2024年02月24日23lyhabc

我使用 VC# 创建了一个员工管理应用程序,在首次运行时,它会向用户查询位于远程计算机上的 (.mdf) 数据库的路径。结果路径可能类似于

string dbPath = @"P:\remoteComputer\public\StaffTool\ExamplePersonnelDatabase.mdf"; 

然后我将这个字符串放入连接字符串模板中:

string dbConnectTemplate = @"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True"; 
string dbConnectionString = String.Format(dbConnectionTemplate,dbPath); 

然后我尝试连接到数据库 LINQ to SQL 样式

ManagementDBDataContext db = new ManagementDBDataContext( 
                dbConnectionString); 

此时,会弹出一个错误提示

The file "P:\remoteComputer\public\StaffTool\ExamplePersonnelDatabase.mdf" is on a network path that is not supported for database files.

An attempt to attach an auto-named database for file P:\remoteComputer\public\StaffTool\ExamplePersonnelDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

由于我对数据库比较陌生,所以我完全看不懂这个消息。显然,该文件不在 UNC 共享上。

有什么想法吗?


Jim Lamb 建议我连接到一个远程运行的 SQL 服务器实例。考虑到我使用的是 LINQ to SQL,我需要进行哪些重构才能实现这一点?其他想法仍然受欢迎 - 尤其是“按下此按钮,一切都会起作用”的解决方案。


另一个线索:一位同事说,过去有一些方法可以通过控制面板->管理工具->数据源(ODBC) 进行操作,这样就可以从我的计算机上查看远程数据库,就好像它是本地数据库一样。除此之外,同事不知道更多细节。

请您参考如下方法:

您正在尝试通过网络连接连接到另一台机器上的数据库文件,SQL Express 不支持这种连接。您需要制作一个本地副本并附加到该副本,或者连接到与 MDF 文件在同一台计算机上运行的 SQL 实例。