如何打开也是项目资源的PDF文件?
我有一个PDF文件,我已将其作为资源导入到我的项目中。 该文件是一个帮助文档,因此我希望能够将其包含在每个部署中。 我希望能够通过单击按钮打开此文件。
我已将构建操作设置为“Embedd Resource”。 所以现在我希望能够打开它。 但是,当我尝试访问资源时 – My.Resources.HelpFile
– 它是一个字节数组。 如果我知道最终用户有一个适合打开PDF文档的程序,我该怎么做?
如果我错过了上一个问题,请指出正确的方向。 我发现了几个关于在应用程序中打开PDF的问题,但我不在乎Adobe Reader是否单独打开。
创建一个新流程:
string path = Path.Combine(Directory.GetCurrentDirectory(), "PDF-FILE.pdf"); Process P = new Process { StartInfo = {FileName = "AcroRd32.exe", Arguments = path} }; P.Start();
为了使其正常工作,必须将Visual Studio设置“ Copy to Output Directory
设置为Copy Always
为PDF文件Copy Always
。
从资源中查看这个易于打开的pdf文件。
private void btnHelp_Click(object sender, EventArgs e) { String openPDFFile = @"c:\temp\pdfName.pdf"; System.IO.File.WriteAllBytes(openPDFFile, global::ProjectName.Properties.Resources.resourcePdfFileName); System.Diagnostics.Process.Start(openPDFFile); }
如果PDF的唯一要点是由PDF阅读器打开,请不要将其作为资源嵌入。 相反,让您的安装将其复制到合理的位置(您可以将它放在EXE所在的位置),然后从那里运行它。 没有必要一遍又一遍地复制它。
“ReferenceGuide”是我添加到资源中的pdf文件的名称。
using System.IO; using System.Diagnostics; private void OpenPdfButtonClick(object sender, EventArgs e) { //Convert The resource Data into Byte[] byte[] PDF = Properties.Resources.ReferenceGuide; MemoryStream ms = new MemoryStream(PDF); //Create PDF File From Binary of resources folders helpFile.pdf FileStream f = new FileStream("helpFile.pdf", FileMode.OpenOrCreate); //Write Bytes into Our Created helpFile.pdf ms.WriteTo(f); f.Close(); ms.Close(); // Finally Show the Created PDF from resources Process.Start("helpFile.pdf"); }
File.Create("temp path"); File.WriteAllBytes("temp path", Resource.PDFFile)
您需要将资源转换为可以使用您的文件的程序可接受的格式。
执行此操作的一种方法是将资源的内容写入文件(临时文件),然后启动将其指向文件的程序。
是否可以将资源直接提供给程序取决于程序。 我不确定是否可以使用Adobe Reader完成。
要将资源内容写入文件,您可以创建MemoryStream类的实例,并将您的字节数组传递给其构造函数
这应该有帮助 – 我经常使用这段代码来打开各种可执行文件,等等……我已经嵌入了这些资源。
private void button1_Click(object sender, EventArgs e) { string openPDFfile = @"c:\temp\pdfName.pdf"; ExtractResource("WindowsFormsApplication1.pdfName.pdf", openPDFfile); Process.Start(openPDFfile); } void ExtractResource( string resource, string path ) { Stream stream = GetType().Assembly.GetManifestResourceStream( resource ); byte[] bytes = new byte[(int)stream.Length]; stream.Read( bytes, 0, bytes.Length ); File.WriteAllBytes( path, bytes ); }