简体   繁体   English

从列表框中读取文件

[英]Read file from listbox

I have some code that will load full file names (ex.F:\\logs\\1234.log) into a listbox depending on the directory the user chooses. 我有一些代码可以将完整的文件名(例如F:\\ logs \\ 1234.log)加载到列表框中,具体取决于用户选择的目录。 When the user selects one or more of the files and clicks the output button, I want the code to read through each selected file. 当用户选择一个或多个文件并单击输出按钮时,我希望代码读取每个选定的文件。 Before, I was using a combobox and the code: 之前,我使用的是组合框和代码:

StreamReader sr = new StreamReader(comboBox1.Text);

This obviously does not work for listboxes. 这显然不适用于列表框。 What is the simplest way to have the program read the user selected file(s) from the listbox? 使程序从列表框中读取用户选择的文件的最简单方法是什么?

You should have been more clear in your original question... but if you need to read all the files: 您应该在最初的问题中更加清楚...但是,如果您需要阅读所有文件,请执行以下操作:

        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
        }

If you are choocing one file per time to open, then a solution would be as follows: 如果您每次选择打开一个文件,那么解决方案如下:

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

Then, to get to the file path selected: 然后,转到选定的文件路径:

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);
       // ..
}

What you can do it to create a generic list, which will hold all the text from selected files: 您可以执行以下操作来创建通用列表,该列表将保存所选文件中的所有文本:

    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);
    }

I think in your example when you explicitly said "as simple as possible" to read the file, would be best to use File.ReadAllText() method, better then using StreamReader class. 我认为在您的示例中,当您明确地说“尽可能简单”地读取文件时,最好使用File.ReadAllText()方法,最好使用StreamReader类。

To access all selected items in a ListBox you can use the SelectedItems property: 要访问列表框中的所有选定项目,可以使用SelectedItems属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM