0

这是我的代码:

protected void Button1_Click(object sender, EventArgs e)
{


    FileInfo SelectedFileInfo = (FileInfo)ListBox1.SelectedItem;

    StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
    string CurrentLine = "";
    //int LineCount = 0;
    while(FileRead.Peek() != -1)
    {
        CurrentLine = FileRead.ReadLine();
        //LineCount++;
        //if(LineCount % 5 == 2)
        {
            ListBox2.Items.Add(CurrentLine);
        }
    }
    FileRead.Close(); 
}

但抛出异常:

无法将类型“System.Web.UI.WebControls.ListItem”转换为“System.IO.FileInfo”

4

1 回答 1

1

填充列表框时,使用文件名而不是 FileInfo 然后在 Button1_Click 中时,使用ListBox1.SelectedValue获取选定的文件名

    protected void Button1_Click(object sender, EventArgs e)
    {
        ListBox2.Items.Clear();
        if (ListBox1.SelectedIndex > -1)
        {
            string filename = ListBox1.SelectedValue;

            StreamReader FileRead = new StreamReader(filename);
            string CurrentLine = "";
            //int LineCount = 0;
            while (FileRead.Peek() != -1)
            {
                CurrentLine = FileRead.ReadLine();
                ListBox2.Items.Add(CurrentLine);
            }
            FileRead.Close();
        }
        else
        {
            ListBox2.Items.Add("Please select a file first");
        }
    }

    protected void Btn_Load_Click(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\errorlog");
        FileInfo[] Files = dinfo.GetFiles("*.txt");
        foreach (FileInfo file in Files)
        {
            ListBox1.Items.Add(file.FullName);

        }
    }

}

于 2013-06-28T19:03:58.867 回答