Getting a binary file from resource in C#
I am having a bit of a problem, I am trying to get a PDF as a resource in my application. At this point I have a fillable PDF that I have been able to store as a file next to the binary, but now I am trying to embed the PDF as a resource in the binary.
byte[] buffer;
try
{
s = typeof(BattleTracker).Assembly.GetManifestResourceStream("libReports.Resources.DAForm1594.pdf");
buffer = new byte[s.Length];
int read = 0;
do
{
read = s.Read(buffer, read, 32768);
} while (read > 0);
}
catch (Exception e)
{
throw new Exception("Error: could not import report:", e);
}
// read existing PDF document
PdfReader r = new PdfReader(
// optimize memory usage
buffer, null
);
开发者_高级运维Every time I run the code I get an error saying "Rebuild trailer not found. Original Error: PDF startxref not found".
When I was just opening the file via a path to the static file in my directory it worked fine. I have tried using different encodings UTF-8, UTF-32, UTF-7, ASCII, etc etc.... As a side note I had the same problem with getting a Powerpoint file as a resource, I was finally able to fix that problem by converting the Powerpoint to xml and using that. I have considered doing the same for the PDF but I am referencing elements by field name which does not seem to work with XML PDFs.
Can anyone help me out with this?
Change the code in your try
block to this:
using (s = typeof(BattleTracker).Assembly.GetManifestResourceStream
("libReports.Resources.DAForm1594.pdf"))
{
buffer = new byte[(int)s.Length];
s.Read(buffer, 0, (int)s.Length);
}
I assume that you have the correct path to your resource, and that its Build Action
property is set to Embedded Resource
.
精彩评论