[英]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 我需要从OpenFileDialog获取用户选择的文件的路径,但无法将其传递给PDFReader
1) you cannot use a class variable in a static
method so accessing ofd
in this line: 1)您不能在
static
方法中使用类变量,因此在此行中访问ofd
:
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.
对于非静态字段“ ofd”,需要一个对象实例。
2) It seems that you are not calling your method. 2)似乎您没有在调用您的方法。 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: 然后,您需要在方法内部使用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
现在返回的字符串应该出现在您的
richTextBox1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.