应用程序的想法很简单,给应用程序一个路径,应用程序将每个文件的路径写入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 âo&psolher d) doိiniᖭ</p>
icon_Áq偩侉₳㪏ံ�ぞ鵃_䑋屡犯1]
MANAFor줡�
编辑[问题已解决]
我所要做的就是:1-将文件名转换为 UTF8-Bytes 2-将 UTF8-Bytes 转换回字符串
这是方法:
byte[] FilestoBytes = System.Text.Encoding.UTF8.GetBytes(Info.Name);
string utf8 = System.Text.Encoding.UTF8.GetString(FilestoBytes);