从列表框中读取文件

时间:2012-07-24 17:27:19

标签: c# winforms listbox

我有一些代码可以将完整的文件名(例如:ex:F:\ logs \ 1234.log)加载到列表框中,具体取决于用户选择的目录。当用户选择一个或多个文件并单击输出按钮时,我希望代码读取每个选定的文件。之前,我使用的是组合框和代码:

StreamReader sr = new StreamReader(comboBox1.Text);

这显然不适用于列表框。让程序从列表框中读取用户所选文件的最简单方法是什么?

4 个答案:

答案 0 :(得分:0)

你原来的问题应该更清楚......但如果你需要阅读所有文件:

        var items = listBox.SelectedItems;
        foreach (var item in items)
        {
            string fileName = listBox.GetItemText(item);
            string fileContents = System.IO.File.ReadAllText(fileName);
            //Do something with the file contents
        }

答案 1 :(得分:0)

如果您每次都要选择一个文件来打开,那么解决方案如下:

string[] files = Directory.GetFiles(@"C:\");
listBox1.Items.Clear();
listBox1.Items.AddRange(files);

然后,要进入所选的文件路径:

if (listBox1.SelectedIndex >= 0)
{ // if there is no selectedIndex, property listBox1.SelectedIndex == -1
       string file = files[listBox1.SelectedIndex];
       FileStream fs = new FileStream(file, FileMode.Open);
       // ..
}

答案 2 :(得分:0)

你可以做些什么来创建一个通用列表,它将保存所选文件中的所有文本:

    void GetTextFromSelectedFiles()
    {
        List<string> selectedFilesContent = new List<string>();
        for (int i = 0; i < listBox1.SelectedItems.Count; i++)
        {
            selectedFilesContent.Add(ReadFileContent(listBox1.SelectedItems.ToString()));
        }

        //when the loop is done, the list<T> holds all the text from selected files!
    }

    private string ReadFileContent(string path)
    {
        return File.ReadAllText(path);
    }

我认为在您的示例中,当您明确表示“尽可能简单”来阅读文件时,最好使用 File.ReadAllText()方法,最好使用StreamReader类。

答案 3 :(得分:0)

要访问ListBox中的所有选定项,您可以使用SelectedItems属性:

foreach (string value in listBox1.SelectedItems)
{
    StreamReader sr = new StreamReader(value);
    ...
}
相关问题