想实现类似我的电脑的功能
指定路径后能显示路径下所有的文件.我用的ListView控件,但是不会实现自动搜索文件并以图标的方式显示.请帮忙

解决方案 »

  1.   

    用TreeView显示,然后当选择的时候遍历该子目录下的文件,若要显示该目录下的所有文件,可再加一ListView,在ListView中显示当前路径下的文件,至于文件图标,可以放到ImageList中或者根据文件类型取相应的图片名称进行显示,具体操作可参考SDK
      

  2.   

    [C#] 
    using System;
    using System.IO;class Test 
    {
        public static void Main() 
        {
            try 
            {
                // Only get subdirectories that begin with the letter "p."
                string[] dirs = Directory.GetDirectories(@"c:\", "p*");
                Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length);
                foreach (string dir in dirs) 
                {
                    Console.WriteLine(dir);
                }
            } 
            catch (Exception e) 
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
        }
    }
      

  3.   

    这个东西无非就是一个目录的查询,在C#中没写过,在C++下写过这样的。不过建议楼主把查询目录的代码放到线程中,不然如果文件很多的 话会影响系统的运行。
    在C#中好象可以用foreach(f in dir)和foreach(dir in dirs);下面是我在C++中写的代码,希望对你有所帮助!
    bool __fastcall TMyThread::FileSearch(AnsiString sourceDir)
    {
       TSearchRec sr;
       AnsiString strDir;
       AnsiString strFile;
       int Attr = 0;
       Attr|=faAnyFile;   if(sourceDir == "")
         return FALSE;
       if(!DirectoryExists(sourceDir))
         return FALSE;   //统一sourceDir的最后一个字符为
       if(sourceDir[sourceDir.Length()] != '\\')
         sourceDir = sourceDir + "\\";
       if(FindFirst(sourceDir+"\\*.*",Attr,sr)==0)
       {
          try
          {
            do
            {
              if(sr.Name == "." || sr.Name == "..")
                continue;          if(sr.Attr == faDirectory)
              {// 是目录就递归查找
                FileSearch(sourceDir+sr.Name);          }
              else
              {// 是文件记录到数据库中
                 strFile=sourceDir+sr.Name;
                 frMain->txt_info->Lines->Add(strFile);
                 //add to database             AnsiString fullp=strFile;
                 AnsiString fp=ExtractFilePath(fullp);
                 int co=fullp.Length()-fp.Length();
                 int p=fp.Length()+1;
                 AnsiString fn=fullp.SubString(p,co);
                  DM->Qry->Connection=DM->adoCon;
                    DM->Qry->Close();
                    DM->Qry->SQL->Clear();
                    DM->Qry->SQL->Add("insert into FileInfo(FilePath,FileName,FileStatues) values(:1,:2,:3)");
                    DM->Qry->Parameters->ParamByName("1")->Value=fp;
                    DM->Qry->Parameters->ParamByName("2")->Value=fn;
                    DM->Qry->Parameters->ParamByName("3")->Value="true";
                    DM->Qry->ExecSQL();             //add end
               }
             }while(FindNext(sr)== 0);
             FindClose(sr);
          }
          catch(Exception &e)
          {
             FindClose(sr);
          }
       }
       return TRUE;}
      

  4.   

    这个是C#用用来获取驱动器列表的,带有图标
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Runtime.InteropServices;
    namespace Example088_获取系统中可用的驱动器列表
    {
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.ListView listView1;
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null; public Form1()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    } /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows Form Designer generated code
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.listView1 = new System.Windows.Forms.ListView();
    this.SuspendLayout();
    // 
    // listView1
    // 
    this.listView1.Location = new System.Drawing.Point(8, 8);
    this.listView1.Name = "listView1";
    this.listView1.Size = new System.Drawing.Size(208, 152);
    this.listView1.TabIndex = 0;
    this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(224, 165);
    this.Controls.Add(this.listView1);
    this.Name = "Form1";
    this.Text = "Form1";
    this.Load += new System.EventHandler(this.Form1_Load);
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO 
    {
    public IntPtr hIcon; 
    public int iIcon;
    public int dwAttributes; 
    public string szDisplayName; 
    public string szTypeName; 
    } [DllImport("shell32")]
    private static extern int SHGetFileInfo(string pszPath,int dwFileAttributes,ref SHFILEINFO psfi,int cbFileInfo,int uFlags);
    const int SHGFI_ICON = 0x0100;
    const int SHGFI_LARGEICON = 0x0000;  static string[] drives;
    ImageList img=new ImageList(); private void Form1_Load(object sender, System.EventArgs e)
    {
    this.listView1.LargeImageList=img;
    // this.listView1.SmallImageList=img;
    // this.listView1.StateImageList=img; drives=Environment.GetLogicalDrives();
    for(int i=0;i<drives.Length;i++)
    {
    string str_temp=drives[i];
    this.listView1.Items.Add(str_temp);
    this.listView1.Items[i].ImageIndex=i;
    }
    for(int i=0;i<drives.Length;i++)
    {
    SHFILEINFO FileInfo=new SHFILEINFO();
    SHGetFileInfo(drives[i],0,ref FileInfo,Marshal.SizeOf(FileInfo),SHGFI_ICON | SHGFI_LARGEICON); Icon myIcon;
    myIcon=Icon.FromHandle(FileInfo.hIcon);
    img.Images.Add(myIcon); 
    }
    } private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
    {

    }
    }
    }
      

  5.   

    我这还有个跟你说的十分类似的,你稍微改一哈就可以了代码很多,我贴出来,这是一个程序的部分代码,我把有的代码删了的
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;namespace FileManager
    {
    /// <summary>
    /// MyForm 的摘要说明。
    /// </summary>
    public class MyForm : System.Windows.Forms.Form
    {
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Button btnUp;
    private System.Windows.Forms.ImageList imageSmall;
    private System.Windows.Forms.ImageList imageLarge;
    private System.Windows.Forms.ListView FilesView;
    private System.ComponentModel.IContainer components;
    private System.Windows.Forms.TextBox txtCurPath;
    //CurPath存储了每一级目录的全路径
    System.Collections.Specialized.StringCollection CurPath=new 
    System.Collections.Specialized.StringCollection();
    public MyForm()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    try
    {
    //初始路径为My Computer
    this.txtCurPath.Text="My Computer";
    //清空FilesView控件
    this.FilesView.Clear();
    //设置ListView控件显示文件的详细数据
    this.FilesView.View=View.Details;
    //增加ListView控件的一个显示字段,显示磁盘名
    this.FilesView.Columns.Add("本地磁盘",FilesView.Width/3,HorizontalAlignment.Left);
    //用GetLogicalDrives方法将系统中所有磁盘列表放置在字符数组Drv中
    string[] Drv=Directory.GetLogicalDrives();
    //读出数组Drv的长度,即系统中所有驱动器的数量
    int DrvCnt=Drv.Length;
    //遍历所有磁盘驱动器并显示
    for(int i=0;i<DrvCnt;i++)
    {
    //初始化一个ListViewItem对象
    ListViewItem lvi=new ListViewItem();
    //设置磁盘驱动器的名称
    lvi.Text="驱动器"+Drv[i];
    //设置图标
    lvi.ImageIndex=3;
    lvi.Tag=Drv[i];
    //添加到FilesView中
    this.FilesView.Items.Add(lvi);
    }
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    } } /// <summary>
    ///清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.components = new System.ComponentModel.Container();
    this.label1 = new System.Windows.Forms.Label();
    this.txtCurPath = new System.Windows.Forms.TextBox();
    this.FilesView = new System.Windows.Forms.ListView();
    this.imageLarge = new System.Windows.Forms.ImageList(this.components);
    this.imageSmall = new System.Windows.Forms.ImageList(this.components);
    this.btnUp = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(8, 16);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(72, 23);
    this.label1.TabIndex = 0;
    this.label1.Text = "当前路径:";
    // 
    // txtCurPath
    // 
    this.txtCurPath.Location = new System.Drawing.Point(72, 16);
    this.txtCurPath.Name = "txtCurPath";
    this.txtCurPath.Size = new System.Drawing.Size(176, 21);
    this.txtCurPath.TabIndex = 1;
    this.txtCurPath.Text = "";
    // 
    // FilesView
    // 
    this.FilesView.LargeImageList = this.imageLarge;
    this.FilesView.Location = new System.Drawing.Point(0, 64);
    this.FilesView.Name = "FilesView";
    this.FilesView.Size = new System.Drawing.Size(424, 200);
    this.FilesView.SmallImageList = this.imageSmall;
    this.FilesView.TabIndex = 2;
    this.FilesView.View = System.Windows.Forms.View.Details;
    this.FilesView.DoubleClick += new System.EventHandler(this.FilesView_DoubleClick);
    // 
    // imageLarge
    // 
    this.imageLarge.ImageSize = new System.Drawing.Size(16, 16);
    this.imageLarge.TransparentColor = System.Drawing.Color.Transparent;
    // 
    // imageSmall
    // 
    this.imageSmall.ImageSize = new System.Drawing.Size(16, 16);
    this.imageSmall.TransparentColor = System.Drawing.Color.Transparent;
    // 
    // btnUp
    // 
    this.btnUp.Location = new System.Drawing.Point(264, 16);
    this.btnUp.Name = "btnUp";
    this.btnUp.Size = new System.Drawing.Size(88, 23);
    this.btnUp.TabIndex = 3;
    this.btnUp.Text = "返回上级目录";
    this.btnUp.Click += new System.EventHandler(this.btnUp_Click);
    // 
    // MyForm
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(424, 273);
    this.Controls.Add(this.btnUp);
    this.Controls.Add(this.FilesView);
    this.Controls.Add(this.txtCurPath);
    this.Controls.Add(this.label1);
    this.Name = "MyForm";
    this.Text = "FileManager";
    this.Load += new System.EventHandler(this.MyForm_Load);
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
      

  6.   

    [STAThread]
    static void Main() 
    {
    Application.Run(new MyForm());
    } void FillFilesView(string FullName)
    {
    FilesView.Clear();
    //设置ListView控件显示文件的详细数据
    FilesView.View=View.Details;
    //增加ListView控件的一个显示字段,显示文件名
    FilesView.Columns.Add("名称",
    FilesView.Width/3,HorizontalAlignment.Left);
    //增加ListView控件的一个显示字段,显示类型
    FilesView.Columns.Add("类型",
    FilesView.Width/6,HorizontalAlignment.Center);
    //增加ListView控件的一个显示字段,显示大小
    FilesView.Columns.Add("大小",
    FilesView.Width/6,HorizontalAlignment.Right);
    //增加ListView控件的一个显示字段,显示最后的访问时间
    FilesView.Columns.Add("最后访问时间",
    FilesView.Width/3,HorizontalAlignment.Left);
    //得到需要显示内容列表的目录信息
    DirectoryInfo CurDir=new DirectoryInfo(FullName);
    //得到当前目录中的所有文件夹(子目录)
    DirectoryInfo[] dirs=CurDir.GetDirectories();
    //得到当前目录中的所有文件
    FileInfo[] files=CurDir.GetFiles();
    //显示当前目录下的文件夹
    foreach(DirectoryInfo dir in dirs)
    {
    //初始化一个ListViewItem对象
    ListViewItem lvi=new ListViewItem();
    //设置文件夹名称
    lvi.Text=dir.Name;
    //设置图标
    lvi.ImageIndex=0;
    lvi.Tag=dir.FullName;
    //设置类型
    lvi.SubItems.Add("文件夹");
    //文件夹不显示大小,设置为空
    lvi.SubItems.Add("");
    //设置最后访问时间
    lvi.SubItems.Add(dir.LastAccessTime.ToString());
    //添加到FilesView中
    FilesView.Items.Add(lvi);
    }
    //显示当前目录下的文件
    foreach (FileInfo file in files)
    {
    //初始化一个ListViewItem对象
    ListViewItem lvi=new ListViewItem();
    //设置文件名称
    lvi.Text=file.Name;
    //我们通过不同的图标来区分txt文件和其他文件,以便我们对txt文件
    //进行编辑
    if(file.Extension==".txt")
    {
    lvi.ImageIndex=1;
    }
    else
    {
    lvi.ImageIndex=2;
    }
    lvi.Tag=file.FullName;
    //设置类型
    lvi.SubItems.Add("文件");
    //设置文件大小
    lvi.SubItems.Add(file.Length.ToString());
    //设置最后访问时间
    lvi.SubItems.Add(file.LastAccessTime.ToString());
    FilesView.Items.Add(lvi);
    }
    }

    private void FilesView_DoubleClick(object sender, System.EventArgs e)
    {
    try
    {
    //获得所选条目的全名称
    string FullName=FilesView.SelectedItems[0].Tag.ToString();
    //双击txt文件时,进入文本编辑框
    if(FilesView.SelectedItems[0].ImageIndex==1)
    { }
    else 
    //双击其他文件时,直接调用系统函数运行此文件
    if(FilesView.SelectedItems[0].ImageIndex==2)
    System.Diagnostics.Process.Start(FullName);
    else
    //如果双击的是FilesView中的文件夹,则进入它的子目录
    {
    //更新txtCurPath控件
    txtCurPath.Text=FullName;
    //更新FilesView控件
    FillFilesView(FullName);
    //将当前目录的全路径存入CurPath中
    CurPath.Add(FullName);
    }
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

    }    
    private void btnUp_Click(object sender, System.EventArgs e)
    {
    try
    {
    if(CurPath.Count>1)
    {//当前目录不在根目录下,返回上一级目录,同时要调用FillFilesView,
    //对FilesView控件进行更新
    //获得上上一级目录的全路径
    string FullName=CurPath[CurPath.Count-2].ToString();
    //更新txtCurPath控件
    txtCurPath.Text=FullName;
    ////更新FilesView控件
    FillFilesView(FullName);
    //从CurPath中删除当前目录
    CurPath.RemoveAt(CurPath.Count-1);
    }
    else
    {
    //当前目录在根目录下(如C:\),点击“返回上一级目录”按钮后,返回
    //“My Computer”的界面
    if(CurPath.Count==1)
    CurPath.RemoveAt(CurPath.Count-1);
    this.txtCurPath.Text="My Computer";
    //清空FilesView控件
    this.FilesView.Clear();
    //设置ListView控件显示文件的详细数据
    this.FilesView.View=View.Details;
    this.FilesView.Columns.Add("本地磁盘",FilesView.Width/3,HorizontalAlignment.Left);
    //用GetLogicalDrives方法将系统中所有磁盘列表放置在字符数组Drv中
    string[] Drv=Directory.GetLogicalDrives();
    int DrvCnt=Drv.Length;
    //遍历所有磁盘驱动器并显示
    for(int i=0;i<DrvCnt;i++)
    {
    ListViewItem lvi=new ListViewItem();
    lvi.Text="驱动器"+Drv[i];
    lvi.ImageIndex=3;
    lvi.Tag=Drv[i];
    this.FilesView.Items.Add(lvi);
    }
    }
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

    } private void NewFolder_Click(object sender, System.EventArgs e)
    { } private void NewFile_Click(object sender, System.EventArgs e)
    {
    } private void Delete_Click(object sender, System.EventArgs e)
    {
    try
    {
    if(FilesView.SelectedItems.Count==0) return;
    //对文件夹的删除
    if(FilesView.SelectedItems[0].SubItems[1].Text=="文件夹")
    {
    //获得所选文件夹的全名称
    string strDir=FilesView.SelectedItems[0].Tag.ToString();
    DialogResult ret=MessageBox.Show("确定删除文件夹"
    +strDir+"?","确定删除",MessageBoxButtons.OKCancel,
    MessageBoxIcon.Question);
    if(ret==DialogResult.OK)
    {
    //确认后进行删除
    Directory.Delete(strDir,false);
    //获得当前目录的全路径
    string CurFullPath=CurPath[CurPath.Count-1];
    //更新FilesView控件
    FillFilesView(CurFullPath);
    MessageBox.Show("文件夹:"+strDir+"已成功删除!");
    } }
    else
    {//对文件进行删除
    //获得所选文件的全名称
    string strFile=FilesView.SelectedItems[0].Tag.ToString();
    DialogResult ret=MessageBox.Show("确定删除文件"+strFile+"?",
    "确定删除",MessageBoxButtons.OKCancel,
    MessageBoxIcon.Question);
    if(ret==DialogResult.OK)
    {
    //确认后进行删除
    File.Delete(strFile);
    //获得当前目录的全路径
    string CurFullPath=CurPath[CurPath.Count-1];
    //对文件进行删除
    FillFilesView(CurFullPath);
    MessageBox.Show("文件"+strFile+"已成功删除!");
    }
    } }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    } } private void ExitMenu_Click(object sender, System.EventArgs e)
    {
    this.Close();

    } private void ContextmenuItemDelete_Click(object sender, System.EventArgs e)
    {
    try
    {
    if(FilesView.SelectedItems.Count==0) return;
    //对文件夹的删除
    if(FilesView.SelectedItems[0].SubItems[1].Text=="文件夹")
    {
    //获得所选文件夹的全名称
    string strDir=FilesView.SelectedItems[0].Tag.ToString();
    DialogResult ret=MessageBox.Show("确定删除文件夹"
    +strDir+"?","确定删除",MessageBoxButtons.OKCancel,
    MessageBoxIcon.Question);
    if(ret==DialogResult.OK)
    {
    //确认后进行删除
    Directory.Delete(strDir,false);
    //获得当前目录的全路径
    string CurFullPath=CurPath[CurPath.Count-1];
    //更新FilesView控件
    FillFilesView(CurFullPath);
    MessageBox.Show("文件夹:"+strDir+"已成功删除!");
    } }
    else
    {//对文件进行删除
    //获得所选文件的全名称
    string strFile=FilesView.SelectedItems[0].Tag.ToString();
    DialogResult ret=MessageBox.Show("确定删除文件"+strFile+"?",
    "确定删除",MessageBoxButtons.OKCancel,
    MessageBoxIcon.Question);
    if(ret==DialogResult.OK)
    {
    //确认后进行删除
    File.Delete(strFile);
    //获得当前目录的全路径
    string CurFullPath=CurPath[CurPath.Count-1];
    //对文件进行删除
    FillFilesView(CurFullPath);
    MessageBox.Show("文件"+strFile+"已成功删除!");
    }
    } }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

    } private void contextMenu_Popup(object sender, System.EventArgs e)
    {

    } private void MyForm_Load(object sender, System.EventArgs e)
    {

    }

    }
    }