代码之家  ›  专栏  ›  技术社区  ›  Rahul Soni

如何从.NET程序集中检索二进制文件?

  •  3
  • Rahul Soni  · 技术社区  · 15 年前

    我有一个Excel文件要嵌入到我的C程序集中。我已经将XLSX文件的构建操作更改为“Embedded Resource”。

    在运行时,我必须从程序集中检索这个XLSX文件。

    Assembly assembly = Assembly.GetExecutingAssembly();
    StreamReader sr = new StreamReader(assembly.GetManifestResourceStream("AssemblyName.Output.xlsx"), true);
    StreamWriter sw = new StreamWriter(strPath);
    sw.Write(sr.ReadToEnd());
    sr.Dispose();
    sw.Dispose();
    System.Diagnostics.Process.Start(strPath);
    

    正如预期的那样,对于XLSX文件来说,这是失败的,因为它是一个二进制数据。这对文本文件很好。

    我尝试了二进制读/写,但无法运行代码。思想?

    1 回复  |  直到 11 年前
        1
  •  10
  •   Muhammad Hasan Khan    11 年前
    var assembly = Assembly.GetExecutingAssembly();
    
    // don't forget to do appropriate exception handling arund opening and writing file
    using(Stream input = assembly.GetManifestResourceStream("AssemblyName.Output.xlsx"))
    using(Stream output = File.Open("output.xlsx"))
    {
         input.CopyTo(output);
    }
    
    推荐文章