【问题标题】:How can I get the path of a file from an OpenFileDialog and pass it to a PDFReader? (C#)如何从 OpenFileDialog 获取文件的路径并将其传递给 PDFReader? (C#)
【发布时间】:2019-01-29 19:10:35
【问题描述】:
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
    ofd.Filter = "PDF|*.pdf";
    if (ofd.ShowDialog() == DialogResult.OK)
    { 
           richTextBox1.Text = ofd.SafeFileName;
    }

}
public static string pdfText(string path)
{
     //this is the error, I cannot get the path of the File I chose from the OpenFileDialog
    PdfReader reader = new PdfReader(ofd.FileName); 
    string text = string.Empty;

    for (int page = 1; page <= reader.NumberOfPages; page++)
    {
        text = text += PdfTextExtractor.GetTextFromPage(reader, page);

    }
    reader.Close();
    return text;
}

我需要从 OpenFileDialog 中获取用户选择的文件的路径,但我无法将其传递给 PDFReader

【问题讨论】:

  • 错误信息是什么? ofd.FileName 应该为您提供所选文件的完整路径..
  • 可能是你忘记调用方法了?类似于:richTextBox1.Text = pdfText(ofd.SafeFileName); 和方法内部PdfReader reader = new PdfReader(path); ?

标签: c# pdf openfiledialog reader


【解决方案1】:

1) 您不能在 static 方法中使用类变量,因此在此行中访问 ofd

PdfReader reader = new PdfReader(ofd.FileName); 

应该会导致编译器错误消息

对于非静态字段“ofd”,需要一个对象实例。

2)您似乎没有调用您的方法。您需要调用它并将文件名作为参数传递给它

private void button1_Click(object sender, EventArgs e)
{
    ofd.Filter = "PDF|*.pdf";
    if (ofd.ShowDialog() == DialogResult.OK)
    { 
           richTextBox1..Text = pdfText(ofd.SafeFileName);
    }    
}

那你需要在方法内部使用method参数:

public static string pdfText(string path)
{
     //this is the error, I cannot get the path of the File I chose from the OpenFileDialog
    PdfReader reader = new PdfReader(path); // Here use path

现在返回的字符串应该出现在你的richTextBox1

【讨论】:

  • @LouePotente 不客气。欢迎来到 Stack Overflow。请不要忘记访问Herlp center。祝你好运:)
猜你喜欢
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 2010-10-01
相关资源
最近更新 更多