将文件存储在 C# EXE 文件中
对于我来说,将一些文件存储在 EXE 中以复制到选定的位置实际上很有用。 我正在生成 HTML 和 JS 文件,需要复制一些 CSS、JS 和 GIF。
代码片段
System.IO.File.WriteAllBytes(@"C:\MyFile.bin", ProjectNamespace.Properties.Resources.MyFile);
对我不起作用!
在“WriteAllBytes”上它说: “无法从‘System.Drawing.Bitmap’转换为‘byte[]’” 对于图像和 “无法从‘字符串’转换为‘字节[]’” 对于文本文件。
帮助!
更新:下面解决了。
It is actually useful for me to store some files in EXE to copy to selected location.
I'm generating HTML and JS files and need to copy some CSS, JS and GIFs.
Snippet
System.IO.File.WriteAllBytes(@"C:\MyFile.bin", ProjectNamespace.Properties.Resources.MyFile);
doesn't work for me!
On "WriteAllBytes" it says:
"cannot convert from 'System.Drawing.Bitmap' to 'byte[]'"
for image and
"cannot convert from 'string' to 'byte[]'"
for text file.
Help!
UPDATE: Solved below.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将所需的文件添加到解决方案中,然后将其
Build Action
属性设置为Embedded Resource
。这会将文件嵌入到您的 exe 中。 (msdn)然后你只需要写执行 exe 时将文件写入磁盘的代码。
例如:
将
resource.bmp
替换为您的文件名。附录:
如果您将该文件保存在解决方案的子文件夹中,则需要将该子文件夹设为
resource.bmp
路径的一部分。例如:此外,您可能需要将
复制到输出目录
属性设置为始终复制
或如果较新则复制
。Add the files you want to your solution and then set their
Build Action
property toEmbedded Resource
. This will embed the file into your exe. (msdn)Then you just need to write the code to write the file out to disk when the exe is executed.
Something like:
Replace
resource.bmp
with your file name.Addendum:
If you keep the file in a sub-folder in your solution you need to make the sub-folder part of the path to
resource.bmp
. Eg:Also, you may need to set the
Copy To Output Directory
property toCopy Always
orCopy If Newer
.我假设您通过“项目属性”窗口添加了文件。这不允许您添加任意文件,但它支持文本文件、位图等。
对于嵌入的文本文件,请使用
对于图像,请使用
I assume you added the files through the Project Properties window. That does not allow you to add an arbitrary file but it does support TextFiles, Bitmaps and so on.
For an embedded TextFile, use
For an Image, use
您可以将二进制文件嵌入到.resx 文件中。将它们放在文件部分中(看起来您使用了图像部分)。如果您的 .resx 文件生成 .Designer.cs 文件,则它应该可以作为字节数组进行访问。
You can embed binary files in a .resx file. Put them in the Files section (it looks like you used the Images section instead). It should be accessible as an array of bytes if your .resx file generates a .Designer.cs file.
将文件添加到项目资源并将其“构建操作”设置为“嵌入资源”。
现在使用以下代码片段提取任何文件(文本或二进制):
根据本文,不知道它有多深是正确的:http://www.yoda.arachsys.com/csharp/readbinary.html
但它有效。
Add files to project resources and set their "Build Action" as "Embedded Resource".
Now extract any file (text or binary) using this snippet:
Don't know how deep is it correct according to this article: http://www.yoda.arachsys.com/csharp/readbinary.html
but it works.