在 C# 窗口窗体中读取 XML(.rtdl)文件时路径中的非法字符
本文关键字:路径 文件 字符 非法 窗口 窗体 读取 XML rtdl | 更新日期: 2023-09-27 18:33:48
在Windows窗体中,我在面板中有一些标签,我想显示listBox1
的静态值,在该中,它从文件夹中加载(.rtdl(文件的集合。
当用户选择每个时,我想在面板中向labels
显示相应的属性值。
用于填充列表框 1 的代码:
private void Form1_Load(object sender, EventArgs e)
{
PopulateListBox(listBox1, @"C:'TestLoadFiles'", "*.rtdl");
}
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file);
}
}
从列表Box1读取文件的代码:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
FileInfo file = (FileInfo)listBox1.SelectedItem;
DisplayFile(file.FullName);
string path = (string)listBox1.SelectedItem;
DisplayFile(path);
}
private void DisplayFile(string path)
{
string xmldoc = File.ReadAllText(path);
using (XmlReader reader = XmlReader.Create(xmldoc))
{
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "description":
if (!string.IsNullOrEmpty(reader.Value))
label5.Text = reader.Value; // your label name
break;
case "sourceId":
if (!string.IsNullOrEmpty(reader.Value))
label6.Text = reader.Value; // your label name
break;
// ... continue for each label
}
}
}
}
当我选择文件时,它会在using (XmlReader reader = XmlReader.Create(xmldoc))
抛出此错误illegal characters in path
.
请告诉我这里出了什么问题???
XmlReader.Create(string)
将路径作为输入(或流(,而不是实际的文本字符串 - 请参阅此处:http://msdn.microsoft.com/en-us/library/w8k674bf.aspx。
因此,只需删除此行:
string xmldoc = File.ReadAllText(path);
在DisplayFile
改变这一点:
using (XmlReader reader = XmlReader.Create(xmldoc))
对此:
using (XmlReader reader = XmlReader.Create(path))
也就是说,你正在以一种非常困难的方式做事。LINQ to XML 对于您要实现的目标来说要简单得多。
改为在DisplayFile
中尝试此操作:
private void DisplayFile(string path)
{
var doc = XDocument.Load(path);
var ns = doc.Root.GetDefaultNamespace();
var conn = doc.Root.Element(ns + "connection");
label5.Text = conn.Element(ns + "description").Value;
label6.Text = conn.Element(ns + "sourceId").Value;
// and so on
}