本文介绍了嵌入式资源文件在运行时.Net 4不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在运行时访问的文件,我已将其包含在我的项目中,并将其设置为嵌入式资源(它实际上是源文件,我将扩展名更改为.cs.txt以避开VS尝试编译它.没关系,但我还是要提一下,以防万一.当我尝试获取文件时

I have a file I need to access at runtime, I've included it in my project and set it up as embedded resource (it's actually a source file, I changed the extension to .cs.txt to get around VS trying to compile it. That shouldn't matter, but I'm mentioning it anyway just in case).When I try getting the file

var assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream(resourceName);

我得到一个空值.我确保使用的是Namespace.Folder.Filename表示法,但这没有帮助.看来文件实际上不存在,因为当我打电话时

I get a null. I've made sure I'm using the Namespace.Folder.Filename notation, but that didn't help. It appears the file is actually not there, because when I call

assembly.GetManifestResourceNames();

我得到一个空的字符串数组.知道会是什么情况吗?

I get an empty string array. Any idea what could be the case?

推荐答案

所以我通过使用VS资源管理器解决了这个问题.现在,我可以像这样直接访问文件:

So I got around this by using the VS resource manager. Now I can access the file directly like this:

MyNamespace.Properties.Resources.MyFile

我将这种方法推荐给任何人,因为它不仅看起来更清洁,而且更安全.感谢Hans Passant的建议.

I'd recommend this approach to anyone, as it seems not only much cleaner, but safer as well. Thanks Hans Passant for the advice.

这篇关于嵌入式资源文件在运行时.Net 4不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:20