2009-08-14 2 views
0

У меня есть приложение Windows, которое берет данные в текстовых файлах и записывает их в случайный сгенерированный текстовый файл, вроде ведения журналов. Затем есть этот список, в котором перечислены все эти отдельные файлы журналов. Я хочу, чтобы другой список отображал информацию о файле выбранной, 2-й, 7-й, 12-й, ..., (2 + 5n) -й строки текстовых файлов, которые выбираются после списка кнопок info '. Как это можно сделать?Как получить информацию о файле, которая выбрана в спискеBox?

Мой код для обновления первого ListBox является:

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

    } 
+3

........ Что! ?! – Gineer

ответ

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(); 
+0

Не совсем то, что искал плакат, хотя я не могу понять, ЧТО плакат искал ... –

+0

продолжает говорить, что объект типа «System.String» не может быть преобразован в тип «System.IO.FileInfo». –

+0

FileInfo SelectedFileInfo = (FileInfo) listBox1.SelectedItem; это дает ошибку –

Смежные вопросы