Search code examples
c#pdfopenfiledialogreader

How can I get the path of a file from an OpenFileDialog and pass it to a PDFReader? (C#)


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

I need to get the path of the file chosen by the user from the OpenFileDialog but I cant pass it to the PDFReader


Solution

  • 1) you cannot use a class variable in a static method so accessing ofd in this line:

    PdfReader reader = new PdfReader(ofd.FileName); 
    

    should result in an compiler error message that

    for the non-static field 'ofd' an object instance is required.

    2) It seems that you are not calling your method. You need to call it and pass the filename as parameter into it

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

    Then you need to use the method parameter inside the 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
    

    Now the returned string should appear in your richTextBox1