繁体   English   中英

从列表框中读取文件

[英]Read file from listbox

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

StreamReader sr = new StreamReader(comboBox1.Text);

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

您应该在最初的问题中更加清楚...但是,如果您需要阅读所有文件,请执行以下操作:

        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
        }

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

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

您可以执行以下操作来创建通用列表,该列表将保存所选文件中的所有文本:

    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类。

要访问列表框中的所有选定项目,可以使用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