简体   繁体   中英

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. 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.

To access all selected items in a ListBox you can use the SelectedItems property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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