最常用且推荐的方式是使用ConfigurationManager(.NET Framework)或IConfiguration(.NET Core/5+);若需直接读取自定义XML文件,可用XmlDocument或XDocument手动解析,并注意空值检查、文件存在性及敏感信息保护。

在C#中从XML文件读取连接字符串,最常用且推荐的方式是使用 ConfigurationManager(针对传统 .NET Framework)或 IConfiguration(针对 .NET Core / .NET 5+)。但如果你明确需要“直接从自定义XML文件读取”,比如一个叫 config.xml 的独立文件,而不是标准的 app.config 或 appsettings.json,那可以用 XmlDocument 或 XDocument 手动解析。
适用于简单结构、兼容性要求高(如 .NET Framework 4.0+)的场景。假设你的 config.xml 长这样:
读取代码如下:
XmlDocument doc = new XmlDocument();
doc.Load("config.xml");
XmlNode node = doc.SelectSingleNode("//add[@name='DefaultConnection']");
string connStr = node?.Attributes["connectionString"]?.Value ?? string.Empty;
if (!string.IsNullOrEmpty(connStr))
{
Console.WriteLine(connStr);
}推荐用于 .NET Framework 3.5+ 或 .NET Core/5+,语法更现代、可读性更好:
XDocument xdoc = XDocument.Load("config.xml");
string connStr = xdoc
.Root?
.Element("connectionStrings")?
.Elements("add")
.FirstOrDefault(e => e.Attribute("name")?.Value == "DefaultConnection")?
.Attribute("connectionString")?
.Value ?? string.Empty;NullReferenceException
FileNotFoundException,建议用 try-catch 包裹或先用 File.Exists 判断NullReferenceException 能自动识别;若编码异常,可改用 FileNotFoundException 显式指定如果你只是想存连接字符串,其实不必自己解析 XML —— .NET 原生支持:
try-catch 的 File.Exists 节,用 XDocument.Load
new StreamReader("config.xml", Encoding.UTF8),配合 app.config
这些方式自带缓存、热重载、多环境支持,比手写 XML 解析更可靠。
基本上就这些。选哪种方式,取决于你用的是什么框架、XML 是否必须独立存在、以及项目是否已接入配置系统。
以上就是C#怎么从XML文件读取连接字符串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号