建立自己的资源管理器

类别:.NET开发 点击:0 评论:0 推荐:

这篇文章介绍了如何得到本地系统信息,通过使用System.Management和Sysetm.IO 来得到文件夹和文件信息,并且把它们显示到TreeView、ListView控件z之中。

首先可以使用ManagementObjectSearcher类来查询system.management域,来获取返回ManagementOjbectCollection,在这个对象中,包含了我们所需要的信息,包括盘,文件夹,文件,现在让我们来看一下整个源码:

System.Windows.Forms.Splitter splitter1;
  private System.Windows.Forms.MainMenu mainMenu1;
  private System.Windows.Forms.MenuItem menuItem1;
  private System.Windows.Forms.MenuItem menuItem2;
  private System.Windows.Forms.MenuItem menuItem3;
  private System.Windows.Forms.MenuItem menuItem4;
  private System.Windows.Forms.TreeView tvFolders;
  private System.Windows.Forms.ListView lvFiles;
  private System.Windows.Forms.ImageList m_imageListTreeView;
  private System.ComponentModel.IContainer components;
///

这里是ide自动产生的

///

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;
 

   this.Cursor = Cursors.WaitCursor;
  
   tvFolders.Nodes.Clear();//清空树
   nodeTreeNode = new TreeNode("My Computer",0,0);//
   tvFolders.Nodes.Add(nodeTreeNode);

   
   TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;

   ManagementObjectCollection queryCollection = getDrives();
   foreach ( ManagementObject mo in queryCollection)
   {
   
    switch (int.Parse( mo["DriveType"].ToString()))
    {
     case Removable:   //可移动盘
      imageIndex = 5;
      selectIndex = 5;
      break;
     case LocalDisk:   //本地磁盘
      imageIndex = 6;
      selectIndex = 6;
      break;
     case CD:    //光盘
      imageIndex = 7;
      selectIndex = 7;
      break;
     case Network:   //网络驱动盘
      imageIndex = 8;
      selectIndex = 8;
      break;
     default:    //默认
      imageIndex = 2;
      selectIndex = 3;
      break;
    }
    //建立驱动盘的节点
    nodeTreeNode = new TreeNode(mo["Name"].ToString() + "\\" ,imageIndex,selectIndex);

    nodeCollection.Add(nodeTreeNode);

   }


   //Init files ListView
   InitListView();

   this.Cursor = Cursors.Default;

  }

  private void tvFolders_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
  {
   
   this.Cursor = Cursors.WaitCursor;

   //获取当前选择的节点或则文件夹
   TreeNode nodeCurrent = e.Node;

   //清除掉所有的节点
   nodeCurrent.Nodes.Clear();

   if (nodeCurrent.SelectedImageIndex == 0)
   {
    
    PopulateDriveList();
   }
   else
   {
    
    PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);
   }
   this.Cursor = Cursors.Default;
  }
  
  protected void InitListView()
  {
   //开始初始化 ListView 控件
   lvFiles.Clear();  
   //为察看列表框建立头信息栏
   lvFiles.Columns.Add("Name",150,System.Windows.Forms.HorizontalAlignment.Left);
   lvFiles.Columns.Add("Size",75, System.Windows.Forms.HorizontalAlignment.Right);
   lvFiles.Columns.Add("Created", 140, System.Windows.Forms.HorizontalAlignment.Left);
   lvFiles.Columns.Add("Modified", 140, System.Windows.Forms.HorizontalAlignment.Left);

  }

  protected void PopulateDirectory(TreeNode nodeCurrent, TreeNodeCollection nodeCurrentCollection)
  {
   TreeNode nodeDir;
   int imageIndex = 2;  
   int selectIndex = 3; 

            if (nodeCurrent.SelectedImageIndex != 0)
   {
    
    try
    {
     
     if(Directory.Exists(getFullPath(nodeCurrent.FullPath)) == false)
     {
      MessageBox.Show("Directory or path " + nodeCurrent.ToString() + " does not exist.");
     }
     else
     {
      PopulateFiles(nodeCurrent);

      string[] stringDirectories = Directory.GetDirectories(getFullPath(nodeCurrent.FullPath));
      string stringFullPath = "";
      string stringPathName = "";

      //循环搜索整个目录
      foreach (string stringDir in stringDirectories)
      {
       stringFullPath = stringDir;
       stringPathName = GetPathName(stringFullPath);
       
       //创建目录节点
       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)
  {
   //得到文件的数目
   string[] stringSplit = stringPath.Split('\\');
   int _maxIndex = stringSplit.Length;
   return stringSplit[_maxIndex-1];
  }

  protected void PopulateFiles(TreeNode nodeCurrent)
  {
   
   string[] lvData =  new string[4];
   
   InitListView();

   if (nodeCurrent.SelectedImageIndex != 0)
   {
    //检查路径
    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;

      
      foreach (string stringFile in stringFiles)
      {
       stringFileName = stringFile;
       FileInfo objFileSize = new FileInfo(stringFileName);
       lFileSize = objFileSize.Length;
       dtCreateDate = objFileSize.CreationTime; //得到建立文件时候的时间;
       dtModifyDate = objFileSize.LastWriteTime; //得到最后修改文件时候的时间;

       
       lvData[0] = GetPathName(stringFileName);
       lvData[1] = formatSize(lFileSize);
       
       
       if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtCreateDate) == false)
       {
        
        lvData[2] = formatDate(dtCreateDate.AddHours(1));
       }
       else
       {
        
        lvData[2] = formatDate(dtCreateDate);
       }

       
       if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtModifyDate) == false)
       {
        
        lvData[3] = formatDate(dtModifyDate.AddHours(1));
       }
       else       
       {
        
        lvData[3] = formatDate(dtModifyDate);
       }


       
       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)
  {
   //得到完整的路径
   string stringParse = "";
   //移除掉“My Computer"名称
   stringParse = stringPath.Replace("My Computer\\", "");

   return stringParse;
  }
  
  protected ManagementObjectCollection getDrives()
  {
   //收集驱动
   ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
   ManagementObjectCollection queryCollection = query.Get();
   
   return queryCollection;
  }

  protected string formatDate(DateTime dtDate)
  {
   //以短格式得到日期和时间
   string stringDate = "";

   stringDate = dtDate.ToShortDateString().ToString() + " " + dtDate.ToShortTimeString().ToString();

   return stringDate;
  }

  protected string formatSize(Int64 lSize)
  {
   
   string stringSize = "";
   NumberFormatInfo myNfi = new NumberFormatInfo();//根据区域定义如何设置数字格式和如何显示数字格式

   Int64 lKBSize = 0;


   if (lSize < 1024 )
   {
    if (lSize == 0)
    {
     
     stringSize = "0";
    }
    else
    {
     
     stringSize = "1";
    }
   }
   else
   {
    
    lKBSize = lSize / 1024;
    
    stringSize = lKBSize.ToString("n",myNfi);
    //移除掉浮点数
    stringSize = stringSize.Replace(".00", "");
   }

   return stringSize + " KB";

  }

  private void menuItem2_Click(object sender, System.EventArgs e)
  {
   //退出应用程序
   this.Close();
  }

 }
}

本文地址:http://com.8s8s.com/it/it45125.htm