程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C#打造自己的文件浏覽器

C#打造自己的文件浏覽器

編輯:C#基礎知識

  C#的功能十分強大,用它可以輕松地做出屬於自己的文件浏覽器。下面簡單地介紹一下文件浏覽器的大致實現過程。其中涉及的有關這些控件的具體用法可參見C#的聯機幫助。

  你需要用到幾個控件:

  TreeView(用於顯示顯示目錄樹);

  ListView(用於顯示文件和目錄列表);

  Splitter(用於允許用戶調整TreeView和ListView的大小);

  其它的如:MainMenu,ToolBar,StatusBar,ImageList等等就看你的實際需要了。

  首先,新建一個C#項目(Windows應用程序),命名為MyFileView,將窗口命名為mainForm,調整主窗口大小(Size)。添加MainMenu,ToolBar,StatusBar,ImageList等控件。

  然後,添加TreeView控件,命名為treeView,Dock屬性設為Left,再添加Splitter控件,同樣將Dock屬性設為Left。最後添加ListView控件,命名為listView,Dock屬性設為Fill。如下圖所示。

  界面做好了,那麼怎樣才能在這個界面裡顯示文件夾和文件呢?這需要我們添加代碼來實現。

  首先引用以下名字空間:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO ;
using System .Runtime .InteropServices ;
在mainForm_Load事件中添加以下代碼,用於在treeView控件中顯示目錄樹:
private void mainForm_Load(object sender, System.EventArgs e)
//獲取邏輯驅動器
string[] LogicDrives=System.IO .Directory .GetLogicalDrives();
TreeNode[] cRoot =new TreeNode[LogicDrives.Length];
for (int i=0;i< LogicDrives.Length ;i++)
{
TreeNode drivesNode=new TreeNode(LogicDrives[i]);
treeView.Nodes .Add (drivesNode);
if (LogicDrives[i]!="A:\\" && LogicDrives[i]!="B:\\" )
getSubNode(drivesNode,true);
}
}

  其中,getSubNode為一方法,用於獲取子目錄,以創建目錄樹節點,參數:PathName為獲取的子目錄在此節點下創建子節點,參數isEnd:結束標志,true則結束。

private void getSubNode(TreeNode PathName,bool isEnd)
{
if(!isEnd)
return; //exit this
TreeNode curNode;
DirectoryInfo[] subDir;
DirectoryInfo curDir=new DirectoryInfo (PathName.FullPath);
try
{
subDir=curDir.GetDirectories();
}
catch{}
foreach(DirectoryInfo d in subDir)
{
curNode=new TreeNode(d.Name);
PathName.Nodes .Add (curNode);
getSubNode(curNode,false);
}
}

  當鼠標單擊目錄節點左邊的+號時,節點將展開,此時,應在AfterExpand事件中加入以下代碼,以獲取此目錄下的子目錄節點:

private void treeView_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
try
{
foreach(TreeNode tn in e.Node .Nodes )
{
if (!tn.IsExpanded)
getSubNode(tn,true);
}
}
catch{;}
}

  當鼠標單擊選中目錄節點時,右邊的listView控件應顯示此目錄下的文件和目錄,代碼如下:

private void treeView_AfterSelect(object sender,System.Windows.Forms.TreeViewEventArgs e)
{
listView.Items.Clear();
DirectoryInfo selDir=new DirectoryInfo(e.Node.FullPath );
DirectoryInfo[] listDir;
FileInfo[] listFile;
try
{
listDir=selDir.GetDirectories();
listFile=selDir.GetFiles();
}
catch{}
foreach (DirectoryInfo d in listDir)
listView.Items .Add (d.Name,6);
foreach (FileInfo d in listFile)
listView.Items .Add (d.Name);
}

  至此,一個簡單的文件浏覽器就做成了,當然,它還很初級,甚至不能用它打開一個文件,加另外,它也不能顯示文件和目錄的圖標,沒有進行錯誤處理,沒有進行安全控制……它能給你的只是一個思路。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved