0

我有一个包含 1 个或多个文本文件的列表框,我将其作为命令打印。但我不知道如何让流阅读器从列表框中读取?

到目前为止,我得到了这个。:

public void OutputBtn_Click(object sender, EventArgs e)
{
    PrintDocument PrintD = new PrintDocument();
    PrintD.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
    StreamReader SR = new StreamReader("C:\\myfile.txt");
    PrintD.Print();

}

有没有我可以更改 "C:\myfile.txt" 还是必须使用 "foreach" ?

4

1 回答 1

0

你想要这样的东西吗?我不完全理解这个问题

string[] fileEntries = Directory.GetFiles("C:\\temp\\").Where(p => 
                                 p.EndsWith(".txt")).ToArray<string>();
foreach (string fileName in fileEntries)
{
    lb.Items.Add(new ListItem(fileName, fileName);
}

好的,所以您的列表框充满了文件名?

private StreamReader sr;

public void OutputBtn_Click(object sender, EventArgs e)
{
    foreach(var li in lb.Items)
    {
        PrintDocument PrintD = new PrintDocument();
        PrintD.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
        sr = new StreamReader(li.ToString());
        PrintD.Print();        
    }
}

private void PrintDocument_PrintPage(object sender, PrintPageEventArgs ev) 
{
     float linesPerPage = 0;
     float yPos =  0;
     int count = 0;
     float leftMargin = ev.MarginBounds.Left;
     float topMargin = ev.MarginBounds.Top;
     String line = null;

     // Calculate the number of lines per page.
     linesPerPage = ev.MarginBounds.Height  / 
        printFont.GetHeight(ev.Graphics) ;

     // Iterate over the file, printing each line.
     while (count < linesPerPage && ((line = sr.ReadLine()) != null)) 
     {
        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
        ev.Graphics.DrawString (line, printFont, Brushes.Black, 
           leftMargin, yPos, new StringFormat());
        count++;
     }

     // If more lines exist, print another page.
     if (line != null) 
        ev.HasMorePages = true;
     else 
        ev.HasMorePages = false;
}
于 2012-08-15T09:33:06.770 回答