[英]illegal characters in path while reading xml(.rtdl)files in C# windows forms
在Windows窗體中,我在面板中有一些標簽,我想顯示listBox1
中的靜態值,它從文件夾中加載(.rtdl)文件的集合。
當用戶選擇每個時,我想在面板中的labels
上顯示相應的屬性值。
填充listBox1的代碼:
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);
}
}
從listBox1讀取文件的代碼:
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
中拋出此錯誤illegal characters in path
using (XmlReader reader = XmlReader.Create(xmldoc))
。
請告訴我這里有什么問題?
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.