使用C#在datagridview中显示文件和子文件夹 [英] Display files and subfolders in datagridview using C#
本文介绍了使用C#在datagridview中显示文件和子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在Datagridview中显示所有文件夹和子文件夹,但我无法显示放置在某个文件夹中的子文件夹。
我尝试过的事情:
我试过以下代码,在目录中显示文件。
I need to display all the folders and sub folders in the Datagridview but I am unable to display the subfolders which were placed in a certain folder.
What I have tried:
I have tried below code which displayed files in the directory.
void Button1Click(object sender, EventArgs e)
{
//lblmsg.Text="";
int i;
String[]files=System.IO.Directory.GetFiles("E:Files");
List<string> myList = new List<string>();
DataTable table=new DataTable();
table.Columns.Add("File name");
myList.Add("R^ECG^test file1");
myList.Add("E:Files");
// myList.Add("E:Files");
//insert an item in the list
//files.Insert(1, "E:Files");
dataGridView1.Columns.Add(lnk);
for(i=0;i<files.Length;i++)
{
label1.Text+=files[i]+'\n';
myList.Add(files[i]);
// FileStream file= new FileStream(files[i],FileMode.Open);
table.Rows.Add(files[i]);
// MessageBox.Show(files[i]);
}
//string strpath="E:Files";
//MessageBox.Show(files.ToString());
dataGridView1.DataSource=table;
// dataGridView1.DataSource=lnk;
}
推荐答案
为了获取所有文件夹中的所有文件,您需要一个递归, 不管怎样。否则你只会从一个级别获取文件。
GetFiles方法有另一个重载,可以用来搜索子文件夹。看一下 Directory.GetFiles方法(String,String,SearchOption)(系统.IO) [ ^ ],尤其是SearchOption
另一件事是你开始寻找的路径似乎缺少反斜杠。所以尝试使用
In order to get all files from all folders you need a recursion, one way or another. Otherwise you will get files only from one level.
GetFiles method has another overload which can be used to search also from subfolders. Have a look at Directory.GetFiles Method (String, String, SearchOption) (System.IO)[^], especially SearchOption
Another thing is that the path where you start looking for seems to be missing backslash. So try using
System.IO.Directory.GetFiles("E:\\Files"...
这篇关于使用C#在datagridview中显示文件和子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文