[英]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.