自动将文本文件名称添加到组合框

自动将文本文件名称添加到组合框

本文介绍了自动将文本文件名称添加到组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将文本文件的名称自动添加到组合框中?如果是,那么如何?

我有一个组合框,其中包含文本文件的名称,但我需要它在文件夹内查找它们,并且在加载表单时需要它来执行操作.我该怎么做,请帮助我.

Is it possible to add the names of text files to a combo box automatically? If So then how?

I Have a combo Box which contains names of text files but i need it to look for them inside a folder and i need it to do it when the form loads. how do i do this please help me.

推荐答案

private void Form1_Load(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles("DirectoryPath");

    for (int i = 0; i < files.Length; i++)
    {
        comboBox1.Items.Add(files[i]);
    }
}



另外,如果只想显示文件名,则可以使用Path.GetFileName(files [i]);.或Path.GetFileNameWithoutExtension(files [i]);静态Path类中的方法.

注意:万一您不知道可以通过双击表单轻松地生成Form_Load事件处理程序.

如果您还想从子目录(文件夹中的文件夹)中获取文件,则可以执行以下操作:

Directory.GetFiles("DirectoryPath","*.*",SearchOption.AllDirectories);
"*.*"是搜索模式,因此,如果只需要文本文件,则可以将其更改为"* .txt"



also if you want to display just the file name you could use Path.GetFileName(files[i]); or Path.GetFileNameWithoutExtension(files[i]); methods from the static Path class.

Note: Just in case you don''t know you can easily generate a Form_Load event handler by double clicking on your form.

And if you want to get files from sub directories (folders within folders) as well you would do something like this:

Directory.GetFiles("DirectoryPath", "*.*", SearchOption.AllDirectories);
the "*.*" is the search pattern so if you only wanted text files you could change it to "*.txt"


string[] filePaths = Directory.GetFiles(@"c:\dir");
fot (int i = 0; i < filePaths.Length; ++i) {
    string path = filePaths[i];
    Console.WriteLine(System.IO.Path.GetFileName(path));
}


在此for循环中,检查每个文件扩展名以做


Inside this for loop check each files extension to do it

Use Path.GetExtension(string path)


如果是.txt,则将其添加到您的组合框中...

祝你好运.


if it is .txt then add to your combobox...

Good luck..



这篇关于自动将文本文件名称添加到组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:25