首页  ·  知识 ·  编程语言
我的资源管理器
网友  博客园愚翁专栏  .NET  编辑:德仔   图片来源:网络
介绍 这篇文章介绍了如何用System.Management 命名空间的类得到系统驱动器信息和Syse
介绍
 
这篇文章介绍了如何用System.Management 命名空间的类得到系统驱动器信息和Sysetm.IO 命名空间的类得到目录和文件信息在TreeView和ListView中显示出来。
开始应用
首先我们必须在计算机的所有许动器上搜集信息,并且在TreeView中显示他们的名字和驱动器,我们可以询问System.Management命名空间中的ManagementObjectSearcher类来获取驱动器信息,它接受一个SQL就好象查询一个参数并且返回一个ManagementOjbectCollection类包含我们所请求的驱动器信息。现在我们所有的驱动器信息在我们的管理中(例如驱动器名称 ,类型,容量大小等......)
 Collapse//This procedure populate the TreeView with the Drive list
private void PopulateDriveList()
{
    TreeNode nodeTreeNode;
    int imageIndex = 0;
    int selectIndex = 0;
   
    const int Removable = 2;
    const int LocalDisk = 3;
    const int Network = 4;
    const int CD = 5;
    //const int RAMDrive = 6;
   
    this.Cursor = Cursors.WaitCursor;
   
    //clear TreeView
    tvFolders.Nodes.Clear();
    nodeTreeNode = new TreeNode("My Computer",0,0);
    tvFolders.Nodes.Add(nodeTreeNode);
   
    //set node collection
    TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;
   
    //Get Drive list
    ManagementObjectCollection queryCollection = getDrives();
    foreach ( ManagementObject mo in queryCollection)
    {
        switch (int.Parse( mo["DriveType"].ToString()))
        {
            case Removable: //removable drives
                imageIndex = 5;
                selectIndex = 5;
                break;
            case LocalDisk: //Local drives
                imageIndex = 6;
                selectIndex = 6;
                break;
            case CD: //CD rom drives
                imageIndex = 7;
                selectIndex = 7;
                break;
            case Network: //Network drives
                imageIndex = 8;
                selectIndex = 8;
                break;
            default: //defalut to folder
                imageIndex = 2;
                selectIndex = 3;
                break;
        }
       
        //create new drive node
        nodeTreeNode = new TreeNode(mo["Name"].ToString()
            + "\\" ,imageIndex,selectIndex);
       
        //add new node
        nodeCollection.Add(nodeTreeNode);
    }
   
    //Init files ListView
    InitListView();
   
    this.Cursor = Cursors.Default;
}
protected ManagementObjectCollection getDrives()
{
    //get drive collection
    ManagementObjectSearcher query = new
        ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
    ManagementObjectCollection queryCollection = query.Get();
    return queryCollection;
}
目录和文件

当我们在TreeView中点击一个驱动器或者一个目录,我们需要核对驱动器或者目录是否存在,现在我们可以在当前的选择中得到目录(这需要用到System.IO 命名空间中的Directory类)。通过Directory.GetDirectories方法用当前的节点路径作为参数,并且将返回一个目录数组,我们可以循环目录数组得到子节点在当前节点的下面。为了得到当前选择的文件节点,我们必须要使用Directory.GetFiles方法用当前的节点路径作为参数,这将返回这个驱动器或者目录的文件数组。现在我们可以在LISTVEW中显示他们并且通过FileInfo类来得到它们的大小,创建时间,修改时间。
 
 
 
 Collapseprotected void PopulateDirectory(TreeNode nodeCurrent,
    TreeNodeCollection nodeCurrentCollection)
{
    TreeNode nodeDir;
    int imageIndex = 2;
    int selectIndex = 3;
   
    if (nodeCurrent.SelectedImageIndex != 0)
    {    //populate treeview with folders
        try
        {
            if(Directory.Exists(getFullPath(nodeCurrent.FullPath))
                == false)
            {
                MessageBox.Show("Directory or path " +
                    nodeCurrent.ToString() + " does not exist.");
            }
            else
            {    //populate files
                PopulateFiles(nodeCurrent);
               
                string[] stringDirectories =
                    Directory.GetDirectories(getFullPath
                        (nodeCurrent.FullPath));
               
                string stringFullPath = "";
                string stringPathName = "";
               
                foreach (string stringDir in stringDirectories)
                {
                    stringFullPath = stringDir;
                    stringPathName = GetPathName(stringFullPath);
                   
                    //create node for directories
                    nodeDir = new TreeNode(stringPathName.ToString(),
                        imageIndex,selectIndex);
           
                    nodeCurrentCollection.Add(nodeDir);
                }
            }
        }
        catch (IOException e)
        {
            MessageBox.Show("Error:
                Drive not ready or directory does not exist.");
        }
        catch (UnauthorizedAccessException e)
        {
            MessageBox.Show("Error:
                Drive or directory access denided.");
        }
        catch (Exception e)
        {
            MessageBox.Show("Error: " + e);
        }
    }
}
protected string GetPathName(string stringPath)
{
    //Get Name of folder
    string[] stringSplit = stringPath.Split('\\');
   
    int _maxIndex = stringSplit.Length;
   
    return stringSplit[_maxIndex-1];
}
protected void PopulateFiles(TreeNode nodeCurrent)
{
    //Populate listview with files
    string[] lvData =  new string[4];
   
    //clear list
    InitListView();
    if (nodeCurrent.SelectedImageIndex != 0)
    {
        //check path
        if(Directory.Exists((string)
            getFullPath(nodeCurrent.FullPath)) == false)
        {
            MessageBox.Show("Directory or path " +
                nodeCurrent.ToString() + " does not exist.");
        }
        else
        {
            try
            {
                string[] stringFiles = Directory.GetFiles
                    (getFullPath(nodeCurrent.FullPath));
                string stringFileName = "";
                DateTime dtCreateDate, dtModifyDate;
                Int64 lFileSize = 0;
                //loop throught all files
                foreach (string stringFile in stringFiles)
                {
                    stringFileName = stringFile;
                    FileInfo objFileSize = new
                        FileInfo(stringFileName);
                    lFileSize = objFileSize.Length;
                    //GetCreationTime(stringFileName);
                    dtCreateDate = objFileSize.CreationTime;
                    //GetLastWriteTime(stringFileName);
                    dtModifyDate = objFileSize.LastWriteTime;
                    //create listview data
                    lvData[0] = GetPathName(stringFileName);
                    lvData[1] = formatSize(lFileSize);
                           
                    //check if file is in local current
                    //day light saving time
                    if (TimeZone.CurrentTimeZone.
                        IsDaylightSavingTime(dtCreateDate) == false)
                    {
                        //not in day light saving time adjust time
                        lvData[2] = formatDate(dtCreateDate.AddHours(1));
                    }
                    else
                    {
                        //is in day light saving time adjust time
                        lvData[2] = formatDate(dtCreateDate);
                    }
                    //check if file is in local current day
                    //light saving time
                    if (TimeZone.CurrentTimeZone.
                        IsDaylightSavingTime(dtModifyDate) == false)
                    {
                        //not in day light saving time adjust time
                        lvData[3] = formatDate(dtModifyDate.AddHours(1));
                    }
                    else{
                        //not in day light saving time adjust time
                        lvData[3] = formatDate(dtModifyDate);
                    }
                    //Create actual list item
                    ListViewItem lvItem = new ListViewItem(lvData,0);
                    lvFiles.Items.Add(lvItem);
                }
            }
            catch (IOException e)
            {
                MessageBox.Show("Error:
                   Drive not ready or directory does not exist.");
            }
            catch (UnauthorizedAccessException e)
            {
                MessageBox.Show("Error:
                   Drive or directory access denided.");
            }
            catch (Exception e)
            {
                MessageBox.Show("Error: " + e);
            }
        }
    }
}
protected string getFullPath(string stringPath)
{
    //Get Full path string
    stringParse = "";
   
    //remove My Computer from path.
    stringParse = stringPath.Replace("My Computer\\", "");
   
    return stringParse;
}
protected string formatDate(DateTime dtDate)
{
    //Get date and time in short format
    string stringDate = "";
    stringDate = dtDate.ToShortDateString().ToString()
        + " " + dtDate.ToShortTimeString().ToString();
   
    return stringDate;
}
protected string formatSize(Int64 lSize)
{
    //Format number to KB
    string stringSize = "";
    NumberFormatInfo myNfi = new NumberFormatInfo();
    Int64 lKBSize = 0;
   
    if (lSize < 1024 )
    {
        if (lSize == 0)
        {
            //zero byte
            stringSize = "0";
        }
        else
        {
            //less than 1K but not zero byte
            stringSize = "1";
        }
    }
    else
    {
        //convert to KB
        lKBSize = lSize / 1024;
       
        //format number with default format
        stringSize = lKBSize.ToString("n",myNfi);
       
        //remove decimal
        stringSize = stringSize.Replace(".00", "");
    }
   
    return stringSize + " KB";
}
 
本文作者:网友 来源:博客园愚翁专栏
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读