[英]How to get the file info which is selected in a listBox?
我有一個Windows應用程序,該程序將文本框中的數據寫入到隨機生成的文本文件中,並保留日志。 然后是這個列表框,列出了所有這些單獨的日志文件。 我想做的是讓另一個列表框顯示在“列表”按鈕之后選擇的文本文件的第二,第7,第12,...,(2 + 5n)行的所選文件信息。信息”被點擊。 這怎么可能呢?
我更新第一個列表框的代碼是:
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\Ece\Documents\Testings");
// What type of file do we want?...
FileInfo[] Files = dinfo.GetFiles("*.txt");
// Iterate through each file, displaying only the name inside the listbox...
foreach (FileInfo file in Files)
{
listBox1.Items.Add(file.Name + " " +file.CreationTime);
}
}
您要在SelectedIndexChanged事件上獲取選定的項目。 我不建議在另一個列表框中顯示第二部分,但是如果您需要的話,我敢肯定您可以從下面的示例中得出答案。 我個人會有一個richTextBox,然后只讀取文件到那里:
//Get the FileInfo from the ListBox Selected Item
FileInfo SelectedFileInfo = (FileInfo) listBox.SelectedItem;
//Open a stream to read the file
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
//Read the file to a string
string FileBuffer = FileRead.ReadToEnd();
//set the rich text boxes text to be the file
richTextBox.Text = FileBuffer;
//Close the stream so the file becomes free!
FileRead.Close();
或者,如果您堅持使用ListBox,則:
//Get the FileInfo from the ListBox Selected Item
FileInfo SelectedFileInfo = (FileInfo) listBox.SelectedItem;
//Open a stream to read the file
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
string CurrentLine = "";
int LineCount = 0;
//While it is not the end of the file
while(FileRead.Peek() != -1)
{
//Read a line
CurrentLine = FileRead.ReadLine();
//Keep track of the line count
LineCount++;
//if the line count fits your condition of 5n + 2
if(LineCount % 5 == 2)
{
//add it to the second list box
listBox2.Items.Add(CurrentLine);
}
}
//Close the stream so the file becomes free!
FileRead.Close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.