C# 如何将文件夹文件加载到 ListView 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1708239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:09:08  来源:igfitidea点击:

How can I load a folders files into a ListView?

c#listviewfile

提问by Sergio Tapia

I'd like to have a user select a folder with the FolderBrowserDialog and have the files loaded into the ListView.

我想让用户使用 FolderBrowserDialog 选择一个文件夹,并将文件加载到 ListView 中。

My intention is to make a little playlist of sorts so I have to modify a couple of properties of the ListView control I'm assuming. What properties should I set on the control?

我的目的是制作一个小播放列表,所以我必须修改我假设的 ListView 控件的几个属性。我应该在控件上设置哪些属性?

How can I achive this?

我怎样才能做到这一点?

采纳答案by djdd87

Surely you just need to do the following:

当然,您只需要执行以下操作:

    FolderBrowserDialog folderPicker = new FolderBrowserDialog();
    if (folderPicker.ShowDialog() == DialogResult.OK)
    {

        ListView1.Items.Clear();

        string[] files = Directory.GetFiles(folderPicker.SelectedPath);
        foreach (string file in files)
        {

            string fileName = Path.GetFileNameWithoutExtension(file);
            ListViewItem item = new ListViewItem(fileName);
            item.Tag = file;

            ListView1.Items.Add(item);

        }

    }

Then to get the file out again, do the following on a button press or another event:

然后要再次取出文件,请在按下按钮或其他事件时执行以下操作:

    if (ListView1.SelectedItems.Count > 0)
    {

        ListViewItem selected = ListView1.SelectedItems[0];
        string selectedFilePath = selected.Tag.ToString();

        PlayYourFile(selectedFilePath);

    }
    else
    {
        // Show a message
    }

For best viewing, set your ListView to Details Mode:

为了获得最佳查看效果,请将您的 ListView 设置为详细信息模式:

ListView1.View = View.Details;

回答by TLiebe

A basic function could look like this:

一个基本函数可能如下所示:

    public void DisplayFolder ( string folderPath )
    {
        string[ ] files = System.IO.Directory.GetFiles( folderPath );

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

回答by Sharmila

List item

项目清单

private void buttonOK_Click_1(object sender, EventArgs e)

私有无效按钮OK_Click_1(对象发送者,EventArgs e)

    {

        DirectoryInfo FileNm = new DirectoryInfo(Application.StartupPath);
        var filename = FileNm.GetFiles("CONFIG_*.csv");

//Filename CONFIG_123.csv,CONFIG_abc.csv,etc

//文件名CONFIG_123.csv、CONFIG_abc.csv等

       foreach(FileInfo f in filename)
        listViewFileNames.Items.Add(f.ToString());

    }