You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

System.NotSupportedException错误修复:连接我的文档中LocalDB数据库

修复LocalDB连接「我的文档」中数据库的路径格式错误

原代码

string dbPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dbPath = Path.Combine(dbPath, "Database1.mdf");
cn = new SqlConnection (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory| "+dbPath+";Integrated Security=True");
GetAllRecords();

运行时错误

System.NotSupportedException: 'The given path's format is not supported.'

问题分析

连接字符串中同时混用了|DataDirectory|占位符和完整物理路径dbPath,生成了类似|DataDirectory| C:\Users\XXX\Documents\Database1.mdf的无效路径格式,LocalDB无法识别这种混合写法。

修复方案

直接移除连接字符串中的|DataDirectory| ,使用已拼接好的完整物理路径即可。推荐用字符串插值构建连接字符串,避免拼接时的空格或格式问题:

string dbPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dbPath = Path.Combine(dbPath, "Database1.mdf");
// 使用字符串插值构建连接字符串,格式更清晰
cn = new SqlConnection($"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename={dbPath};Integrated Security=True");
GetAllRecords();

如果偏好传统字符串拼接写法,修正后的代码如下:

string dbPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dbPath = Path.Combine(dbPath, "Database1.mdf");
cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + dbPath + ";Integrated Security=True");
GetAllRecords();

内容的提问来源于stack exchange,提问作者Shashika Lakshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:05:32