private
void btnBrowers_Click(
object sender, EventArgs e)
{
OpenFileDialog ofd =
new OpenFileDialog();
ofd.Filter =
"
htm files (*.htm)|*.htm
";
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
CreateFirefoxFile(ofd.FileName);
}
catch
{
MessageBox.Show(
"
您选择的文件可能不是delicious书签的备份文件,或者其他未知原因造成程序出错。欢迎到 http://www.cnblogs.com/BenjaminYao 与作者联系,共同完善。
",
"
出错
", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
///
<summary>
///
哈希表分隔符,连接key使用,避免与普通分隔符相同,比如“-”
///
</summary>
private
static
readonly
string keySeparator =
"
*#*#*
";
private
void CreateFirefoxFile(
string fileName)
{
if (!File.Exists(fileName))
{
MessageBox.Show(
"
文件不存在
",
"
出错
", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string oldAll = File.ReadAllText(fileName, Encoding.UTF8);
string head = oldAll.Substring(
0, oldAll.IndexOf(
"
<DL><p>
") +
7);
string oldBody = oldAll.Substring(head.Length, oldAll.IndexOf(
"
</DL><p>
") - head.Length);
string foot = oldAll.Substring(oldAll.IndexOf(
"
</DL><p>
"));
//
生成哈希表
Hashtable hstBody =
new Hashtable();
int i =
1;
//
避免哈希表中的key相同
foreach (
string bookmark
in Regex.Split(oldBody,
"
<DT>
"))
{
if (bookmark.IndexOf(
"
A HREF
") >=
0)
{
//
取出标签名
string key = bookmark.Substring(
bookmark.IndexOf(
"
TAGS=\"
") +
6,
bookmark.IndexOf(
"
\">
") - (bookmark.IndexOf(
"
TAGS=\"
") +
6))
+ keySeparator
+ Convert.ToString(i++);
hstBody.Add(key, bookmark);
}
}
if (hstBody.Count ==
0)
{
MessageBox.Show(
"
没有书签
",
"
警告
", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
//
对哈希表进行排序
ArrayList aKeys =
new ArrayList(hstBody.Keys);
aKeys.Sort();
string tempKey =
string.Empty;
bool isHead =
true;
StringBuilder sbNewBody =
new StringBuilder();
foreach (
string akey
in aKeys)
{
//
插入标签(标签即目录)
if (tempKey.ToLower() != akey.Substring(
0, akey.IndexOf(keySeparator)).ToLower())
{
tempKey = akey.Substring(
0, akey.IndexOf(keySeparator));
if (isHead)
{
sbNewBody.AppendFormat(
"
\n\n<DT><H3 FOLDED ADD_DATE=\"\">{0}</H3> \n<DL><p>\n
", tempKey);
isHead =
false;
}
else
{
sbNewBody.AppendFormat(
"
</DL><p> \n\n<DT><H3 FOLDED ADD_DATE=\"\">{0}</H3> \n<DL><p>\n
", tempKey);
}
}
sbNewBody.Append(
"
<DT>
" + hstBody[akey].ToString());
}
sbNewBody.Append(
"
</DL><p>\n
");
string newBody = sbNewBody.ToString();
head = head.Replace(
"
charset=UTF-8
",
"
charset=gb2312
");
string newAll = head + newBody + foot;
//
生成文件
string newFileName = fileName.Substring(
0, fileName.LastIndexOf(
'
\\
') +
1);
newFileName +=
"
delicious2firefox.htm
";
File.WriteAllText(newFileName, newAll, Encoding.GetEncoding(
"
gb2312
"));
MessageBox.Show(
"
恭喜恭喜,转换成功。将生成的 delicious2firefox.htm 导入 firefox 书签即可。
",
"
成功
", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}