我有一个Windows应用程序,它接收文本框中的数据并将它们写入随机生成的文本文件,有点保存日志。然后有这个列表框列出了所有这些单独的日志文件。我想要做的是让另一个列表框显示所选文件的文件信息,在按钮列表后选择的文本文件的第2,第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);
}
}
答案 0 :(得分:3)
在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();