C#:将iText7 PDF保存到用户通过对话框选择的文件夹中
我会用C#和Windows窗体制作一个简单的程序,通过一些文本框获取用户提供的一些数据,当用户按下按钮时,会显示一个C#:将iText7 PDF保存到用户通过对话框选择的文件夹中,c#,itext,windows-forms-designer,itext7,C#,Itext,Windows Forms Designer,Itext7,我会用C#和Windows窗体制作一个简单的程序,通过一些文本框获取用户提供的一些数据,当用户按下按钮时,会显示一个对话框(我不知道是哪一个),以便浏览pc文件夹并选择保存它的目的地 好的,我使用了一个FolderBrowserDialog(我不知道这是否是正确的),但有一个问题:为了用itext7存储PDF,我必须给出一个环境.SpecialFolder变量,而方法selectedPath()获取formBrowserDialog的用户路径会返回一个字符串 我试图以某种方式将字符串转换为环境。
对话框
(我不知道是哪一个),以便浏览pc文件夹并选择保存它的目的地
好的,我使用了一个FolderBrowserDialog
(我不知道这是否是正确的),但有一个问题:为了用itext7存储PDF,我必须给出一个环境.SpecialFolder
变量,而方法selectedPath()
获取formBrowserDialog的用户路径会返回一个字符串
我试图以某种方式将字符串
转换为环境。SpecialFolder
,但我总是得到一个系统。ArgumentException
这是我的密码:
string name = txtName.Text;
//
//bla bla bla getting the parameters given by the user
//...
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
string folder="";
//"fbd" is the FolderBrowserDialog
if (fbd.ShowDialog() == DialogResult.OK)
{
//here I get the folder path (I hope I've chosen the right dialog for this scope, which is a FolderBrowserDialog)
folder = fbd.SelectedPath;
//starting my pdf generation
//here is my attempt to write something in order to parse the path string into an Environment.SpecialFolder type, to use it as a parameter in getFolderPath()
Environment.SpecialFolder path = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), folder);
//here it's supposed to give to the GetFolderPath method the Environment.SpecialFolder type.
var exportFolder = Environment.GetFolderPath(path); //ON THIS LINE I GET THE EXCEPTION
var exportFile = System.IO.Path.Combine(exportFolder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("
//bla bla bla writing my things on it
"));
}
}
//pdf creation ends
}
为了简化所有这些,您根本不需要
Environment.SpecialFolder
变量,也不需要将其作为参数传递
引发异常的原因是您试图将字符串
解析到环境中。当无法将字符串解析为一个字符串时,SpecialFolder
变量枚举
您可以查看包含的枚举列表。我敢打赌,您选择的特定路径与这些路径都不匹配
以下是您的代码当前正在执行的操作:
Environment.SpecialFolder
变量(如果您确实
如果能够解析它,您将得到刚开始的结果
与)string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
//You select the folder here
if (fbd.ShowDialog() == DialogResult.OK)
{
string folder = fbd.SelectedPath;
//combine the path of the folder with the pdf name
string exportFile = System.IO.Path.Combine(folder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("//bla bla bla writing my things on it"));
}
}
//Pdf creation ends
}
如果我做了这么多无意义的编码,我很抱歉,但我完全不知道什么是环境。特殊文件夹变量,我不理解文档,也不在学校学习。我想你的意思是将“文件夹”放入Path.IO.Combine方法是的,正确。不用担心。你会发现最重要的事情不能在学校里教。