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

发布于 2024-08-27 05:00:53 字数 520 浏览 1 评论 0原文

我有一个 Excel 文件,我想将其嵌入到我的 C# 程序集中。我已将 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 文件,此操作会失败,因为它是二进制数据。这对于文本文件来说可以很好地工作。

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

I have an excel file that I want to embed in my C# assembly. I have changed the build action of the XLSX file to "Embedded Resource".

During runtime, I have to retrieve this XLSX file from the assembly.

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);

As expected, this fails for the XLSX file since it is a binary data. This could works well with a text file.

I tried binary read/write, but I am not able to get the code running. Thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

合约呢 2024-09-03 05:00:53
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);
}
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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文