應用的想法很簡單,應用程序給出的路徑,應用程序寫入每個file`s路徑轉換成XML,我面臨的問題是文件名可以有無效字符,並且使應用程序停止工作,這是我用它來解析文件信息轉換成XML代碼:解析無效字符到XML
// the collecting details method
private void Get_Properties(string path)
{
// Load the XML File
XmlDocument xml = new XmlDocument();
xml.Load("Details.xml");
foreach (string eachfile in Files)
{
try
{
FileInfo Info = new FileInfo(eachfile);
toolStripStatusLabel1.Text = "Adding : " + Info.Name;
// Create the Root element
XmlElement ROOT = xml.CreateElement("File");
if (checkBox1.Checked)
{
XmlElement FileName = xml.CreateElement("FileName");
FileName.InnerText = Info.Name;
ROOT.AppendChild(FileName);
}
if (checkBox2.Checked)
{
XmlElement FilePath = xml.CreateElement("FilePath");
FilePath.InnerText = Info.FullName;
ROOT.AppendChild(FilePath);
}
if (checkBox3.Checked)
{
XmlElement ModificationDate = xml.CreateElement("ModificationDate");
string lastModification = Info.LastAccessTime.ToString();
ModificationDate.InnerText = lastModification;
ROOT.AppendChild(ModificationDate);
}
if (checkBox4.Checked)
{
XmlElement CreationDate = xml.CreateElement("CreationDate");
string Creation = Info.CreationTime.ToString();
CreationDate.InnerText = Creation;
ROOT.AppendChild(CreationDate);
}
if (checkBox5.Checked)
{
XmlElement Size = xml.CreateElement("Size");
Size.InnerText = Info.Length.ToString() + " Bytes";
ROOT.AppendChild(Size);
}
xml.DocumentElement.InsertAfter(ROOT, xml.DocumentElement.LastChild);
// +1 step in progressbar
toolStripProgressBar1.PerformStep();
success_counter++;
Thread.Sleep(10);
}
catch (Exception ee)
{
toolStripProgressBar1.PerformStep();
error_counter++;
}
}
toolStripStatusLabel1.Text = "Now Writing the Details File";
xml.Save("Details.xml");
toolStripStatusLabel1.Text = success_counter + " Items has been added and "+ error_counter +" Items has Failed , Total Files Processed ("+Files.Count+")";
Files.Clear();
}
下面是XML怎麼樣子的細節一代又:我想字符
<?xml version="1.0" encoding="utf-8"?>
<Files>
<File>
<FileName>binkw32.dll</FileName>
<FilePath>D:\ALL DLLS\binkw32.dll</FilePath>
<ModificationDate>3/31/2012 5:13:56 AM</ModificationDate>
<CreationDate>3/31/2012 5:13:56 AM</CreationDate>
<Size>286208 Bytes</Size>
</File>
<File>
實例解析到XML沒有問題:
BX] GC^O^_nI_C {jv_rbp & 1b_H AO & psolher d)做ိiniᖭ
icon_Áq偩侉₳㪏ံぞ鵃_䑋屢1]
MAnaFor줡
EDIT [問題解決]
我不得不做的是: 1轉換的文件名UTF8字節 2-轉換的UTF8字節回串
這裏是方法:
byte[] FilestoBytes = System.Text.Encoding.UTF8.GetBytes(Info.Name);
string utf8 = System.Text.Encoding.UTF8.GetString(FilestoBytes);