做了很久,自己編寫的浏覽器的收藏夾終於解決了,已經成全實現了收藏夾的功能。下面是我的解決方案,帖出來交流交流。歡迎各位高手拍磚。
code//獲取收藏夾路徑
string favorfolder = Environment.GetFolderPath(Environment.SpecialFolder.Favorites); //獲取系統收藏夾路徑
//構造器
public Form1()
{
ListMenuItem(收藏夾ToolStripMenuItem, new DirectoryInfo(favorfolder));
}
public void ListMenuItem(ToolStripMenuItem toolstripmenuitem, FileSystemInfo info) //生成收藏夾菜單的函數,遞歸使用
{
if (!info.Exists) return;
DirectoryInfo dir = info as DirectoryInfo;
//不是目錄
if (dir == null) return;
FileSystemInfo[] files = dir.GetFileSystemInfos();
ToolStripMenuItem[] ShouCangsMenuItem = new ToolStripMenuItem[files.Length];
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
ShouCangsMenuItem[i] = new System.Windows.Forms.ToolStripMenuItem();
//是文件
if (file !=null)
{
if (file.Extension == ".url")
{
ShouCangsMenuItem[i].Image = global::MyWebBrowser2010.Properties.Resources.ie1;//菜單項圖片
string str = file.Name; //獲取收藏夾的文件名(都是URL文件)
str = str.Remove(str.Length - 4); //去掉.url後綴名
ShouCangsMenuItem[i].Text = str; //然後賦值給菜單文本
StreamReader sr = file.OpenText();//獲取文件輸入流
List src = new List();
string source = null;
while ((source = sr.ReadLine()) != null)
{
src.Add(source);//文件所有行添加到List中
}
ShouCangsMenuItem[i].Tag = src;
foreach (string stri in src)
{
if (stri != null)
{
if (stri.StartsWith("URL="))
{
ShouCangsMenuItem[i].ToolTipText = stri.Remove(0,4);//ToolTipText
}
}
}
toolstripmenuitem.DropDownItems.Add(ShouCangsMenuItem[i]); //生成的子菜單添加到上一級菜單
ShouCangsMenuItem[i].Click += new EventHandler(ShouCangsMenuItem_Click); //為生成的子菜單添加單擊消息(可寫一個消息處理函數,這裡就不例出來了)
}
}
//對於子目錄,進行遞歸調用
else
{
DirectoryInfo Direct = files[i] as DirectoryInfo;
ShouCangsMenuItem[i].Text = files[i].Name;
ShouCangsMenuItem[i].Image = global::MyWebBrowser2010.Properties.Resources.folder2;//菜單項圖片
ShouCangsMenuItem[i].ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
ShouCangsMenuItem[i].ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.SizeToFit;
toolstripmenuitem.DropDownItems.Add(ShouCangsMenuItem[i]); //生成的子菜單添加到上一級菜單
ListMenuItem(ShouCangsMenuItem[i], new DirectoryInfo(Direct.FullName)); //遞歸使用,生成子菜單
}
}
}
private void ShouCangsMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = (ToolStripMenuItem)sender;
string[] tar=((List)item.Tag).ToArray();
for (int i = 0; i < tar.Length; i++)
{
if (tar[i] != null)
{
if (tar[i].StartsWith("URL="))
{
getCurrentBrowser().Navigate(tar[i].Remove(0, 4));
}
}
}
}