简体   繁体   English

从C#中的资源获取二进制文件

[英]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. 我有一点问题,我想在我的应用程序中获取PDF作为资源。 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. 此时我有一个可填写的PDF,我可以将其存储为二进制文件旁边的文件,但现在我试图将PDF作为资源嵌入到二进制文件中。

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". 每次我运行代码时都会收到一条错误消息“未找到重建预告片。原始错误:未找到PDF startxref”。

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. 我尝试使用不同的编码UTF-8,UTF-32,UTF-7,ASCII等等....作为旁注,我将Powerpoint文件作为资源遇到了同样的问题,我终于能够解决了通过将Powerpoint转换为xml并使用它来解决这个问题。 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. 我已经考虑过为PDF做同样的事情,但我按字段名称引用元素,这似乎不适用于XML PDF。

Can anyone help me out with this? 任何人都可以帮我解决这个问题吗?

Change the code in your try block to this: try块中的代码更改为:

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 . 我假设您拥有资源的正确路径,并且其Build Action属性设置为Embedded Resource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM