메시지 코드의 리소스 파일을 만들려고합니다. 나는 작은 콘솔 예제를 만들었습니다.이 예제는 객체를 다시 호출하려고 할 때 실패합니다.런타임에 사용할 수있는 리소스 파일에서 클래스 개체를 만들고 호출하는 방법은 무엇입니까?
나는 이것을 MSDN -Creating Resource Files 예제에 기반을 두었지만 단순화하려고 시도한 동안 내가 놓친 부분을 잘 모른다.
코드에서 한 번 실행하여 리소스 파일을 생성하고 해당 파일을 프로젝트에 추가합니다. 그런 다음 리콜 코드를 실행하기 위해 다시 컴파일합니다.
using System;
using System.Reflection;
using System.Resources;
namespace ResourceDemo
{
internal class Program
{
private static void Main(string[] args)
{
bool generateMode = false;
if (generateMode) {
// After running once with generate mode set to true, add the resulting
// "StatusItem.resource" that was created in the .\bin\x86\Debug folder
// to the project.
Generate();
}
else {
// When run the next line generates an exception:
// An unhandled exception of type 'System.Resources.MissingManifestResourceException' occurred in mscorlib.dll
//
// Additional information: Could not find any resources appropriate for the specified culture
// or the neutral culture. Make sure "StatusItems.resources" was correctly embedded or linked
// into assembly "ResourceDemo" at compile time, or that all the satellite assemblies required
// are loadable and fully signed.
StatusItem statusItem = GetResource("2");
Console.WriteLine("Id: {0} Message: {1}", statusItem.Id.ToString(), statusItem.Message);
Console.ReadKey();
}
}
public static void Generate()
{
StatusItem[] statusItem = new StatusItem[4];
// Instantiate an Status object items.
statusItem[0] = new StatusItem(2, "File not found");
statusItem[1] = new StatusItem(3, "Path not found");
statusItem[2] = new StatusItem(4, "Too many open files");
statusItem[3] = new StatusItem(5, "File access denied");
// Define a resource file named StatusItems.resx.
using (System.Resources.ResourceWriter rw = new ResourceWriter(@".\StatusItems.resources")) {
for (int i = 0; i < 4; i++) {
rw.AddResource(statusItem[i].Id.ToString(), statusItem[i]);
}
rw.Generate();
}
}
public static StatusItem GetResource(string key)
{
Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Resources.ResourceManager rm = new System.Resources.ResourceManager("StatusItems", Assembly.Load("ResourceDemo"));
return (StatusItem)rm.GetObject(key);
}
[Serializable()]
public class StatusItem
{
public StatusItem(int id, string message)
{
Id = id;
Message = message;
}
public int Id { get; set; }
public string Message { get; set; }
}
}
}
단순히 기존 항목을 프로젝트에 추가했습니다. 나는 ID로 컴파일하고 있는데, 어떤 커맨드 kine을/resource 옵션에 추가합니까? –
@ 리치 : 포함시키려는 .resources 파일에 대해'/ resource' 스위치를 제공하여 csc.exe를 사용하여 명령 줄에서 .cs 파일을 컴파일해야합니다. .resource 파일 형식을 사용하고 프로젝트에 Embedded Resource 항목으로 포함하려는 경우 항목을 원시 데이터로 검색하고 'ResourceReader' 클래스를 직접 읽어 데이터를 읽어야합니다. 개인적으로, .resx 파일 옵션을 사용하면 일반적인 리소스 관리 메커니즘과 가장 잘 통합됩니다. –
그러나 ResXResourceWriter 제품군을 사용하면 추가 단계를 수행하지 않아도됩니까? –