我正在将 .docx 文件嵌入到我的控制台应用程序中,并且我希望能够分发 console.exe 并使用户能够访问其中的 .docx 文件。
我已将 .docx 文件设置为资源(参见图片) - 但是,如果我尝试使用 Resources.Test.docx
来“访问”它,它似乎不存在,而智能感知并没有将其作为一个选项。
编辑
在 winforms 中,我将像这样嵌入资源:
static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
string rn1 = new AssemblyName(args.Name).Name + ".docx";
string rs1 = Array.Find(this.GetType().Assembly.GetManifestResourceNames(), element => element.EndsWith(rn1));
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(rs1))
{
Byte[] assemblydata = new Byte[stream.Length];
stream.Read(assemblydata, 0, assemblydata.Length);
return Assembly.Load(assemblydata);
}
}
}
并像这样访问文件:
Object oFName;
byte[] resourceFile = Properties.Resources.Report;
string destination = Path.Combine(Path.GetTempPath(), "Test.docx");
System.IO.File.WriteAllBytes(destination, resourceFile);
oFName = destination;
编辑2
如果我尝试使用用于 winforms 的代码 AppDomain.CurrentDomain.AssemblyResolve ->
我收到以下错误
A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
Keyword 'this' is not valid in a static property, static method, or static field initializer
最佳答案
您的第一个方法,经过一些修改,应该能够返回资源流。这基本上是您稍微修改一下以读取流的内容:
public static byte[] GetResourceData(string resourceName)
{
var embeddedResource = Assembly.GetExecutingAssembly().GetManifestResourceNames().FirstOrDefault(s => string.Compare(s, resourceName, true) == 0);
if (!string.IsNullOrWhiteSpace(embeddedResource))
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResource))
{
var data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
return data;
}
}
return null;
}
可以使用资源名称调用此方法,并将返回嵌入资源内的所有字节。
关于c# - 在控制台应用程序中访问嵌入式资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085044/