【问题标题】:How to retrieve a binary file from .NET assembly?如何从 .NET 程序集中检索二进制文件?
【发布时间】:2014-03-28 20:35:39
【问题描述】:

我有一个要嵌入到 C# 程序集中的 excel 文件。我已将 XLSX 文件的构建操作更改为“嵌入式资源”。

在运行时,我必须从程序集中检索这个 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 文件失败了,因为它是二进制数据。这可能适用于文本文件。

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

【问题讨论】:

    标签: c# resources embedded-resource


    【解决方案1】:
    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 1970-01-01
      • 2021-12-19
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多