Program Tip

GetManifestResourceStream이 NULL을 반환합니다.

programtip 2020. 10. 15. 21:27
반응형

GetManifestResourceStream이 NULL을 반환합니다.


이것은 C # .NET 4.0 응용 프로그램입니다.

텍스트 파일을 리소스로 포함하고 대화 상자에 표시하려고합니다.

    var assembly = Assembly.GetExecutingAssembly();
    var resourceName = "MyProj.Help.txt";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                string result = reader.ReadToEnd();
                System.Windows.Forms.MessageBox.Show(result, "MyProj", MessageBoxButtons.OK);
            }
        }

솔루션은 MyProjSolution이고 실행 파일은 MyProj.exe입니다. Help.txt는 포함 된 리소스입니다. 그러나 스트림은 null입니다. MyProjSolution.Help.txt 및 MyProjSolution.MyProj.Help.txt를 시도했지만 아무것도 작동하지 않는 것 같습니다.


다음을 사용하여 리소스가 올바르게 포함되었는지 확인할 수 있습니다.

//From the assembly where this code lives!
this.GetType().Assembly.GetManifestResourceNames()

//or from the entry point to the application - there is a difference!
Assembly.GetExecutingAssembly().GetManifestResourceNames()

디버깅 할 때. 그러면 코드가 작성된 어셈블리에 포함 된 모든 리소스의 모든 (정규화 된 이름)이 나열됩니다.

MSDN에서 Assembly.GetManifestResourceNames ()참조하십시오 .

관련 이름을 복사하고 'resourceName'변수에 정의한 이름 대신 사용하십시오.

참고-리소스 이름은 대소 문자를 구분하며 리소스 파일을 잘못 삽입 한 경우 GetManifestResourceNames () 호출에서 반환 된 목록에 표시되지 않습니다. 또한-올바른 어셈블리 (여러 어셈블리를 사용하는 경우)에서 리소스를 읽고 있는지 확인하십시오. 참조 된 어셈블리가 아닌 현재 실행중인 어셈블리에서 리소스를 쉽게 가져올 수 있습니다.

편집-.NET Core .NET Core를 사용하여 포함하는 방법에 대한 자세한 내용
은이 SO 게시물 을 참조하십시오.

매니페스트 정보를 검색하는 것은 비슷해 보입니다 this.GetType().GetTypeInfo().Assembly.GetManifestResourceNames(). 코드가 실행중인 어셈블리에서 매니페스트를 가져 오는 데 사용 하면됩니다.

Assembly.GetExecutingAssembly()아직 .NET Core에서 해당 작업을 수행하는 방법을 찾지 못했습니다! 아는 사람이 있으면 알려 주시면이 답변을 업데이트하겠습니다.


먼저 파일이 프로젝트에 포함되어 있는지 비슷한 문제를 확인한 다음 속성으로 이동하여 해당 파일의 빌드 작업을 Embedded Resource로 설정했습니다. 이것은 나를 위해 일했습니다.


내 null 값의 원인은 다음과 같습니다.

http://adrianmejia.com/blog/2011/07/18/cs-getmanifestresourcestream-gotcha/

리소스 'built action'속성이 'embedded resource'로 설정되지 않은 경우 GetManifestResourceStream 메서드는 항상 NULL을 반환합니다.

필요한 모든 파일 어셈블리로이 속성을 설정 한 후 GetManifestResourceStream은 NULL 대신 corrent 스트림을 반환하기 시작합니다.


경고 일뿐입니다.

파일에 포함 된 리소스로 파일을 지정했지만 해당 빌드 작업 속성이 있어도 파일에 액세스 할 수 없습니다. 머리를 두드리는 데 많은 시간을 낭비했습니다. 이름에 .txt가 추가 된 csharp 코드 파일 (xxx.cs.txt)을 삽입했습니다. 어떤 이유로 GetManifestResourceNames () 및 GetManifestResourceStream () 메서드는 이름에 .cs가 포함 된 파일을 볼 수 없습니다.

나는 그것을 단순히 xxx.txt로 이름을 바꾸었고 모든 것이 잘되었습니다.

기묘한.


포함 된 파일의 "Build Action" 속성을 "Embedded Resource"설정하여 아래에 제공된 줄을 올바르게 실행해야합니다.

Stream stream = assembly.GetManifestResourceStream(resourceName)

파일을 마우스 오른쪽 버튼으로 클릭하고 속성을 클릭 한 다음 "Build Action"속성을 "Embedded Resource"로 설정합니다.

여기에 이미지 설명 입력


Jay 덕분에 디렉토리 이름에 하이픈이 있다는 것을 알았습니다.

ProjectName.ResourceFolder.Sub-Directory becomes ProjectName.ResourceFolder.Sub_Directory when you reference the resource stream.


In my case the problem was that the code looking for the resource was in a different project that the resource itself.

You can only access resources that are in the same project the code is. I thought I could put all my resources in the web page project, but I need images in the mail project too.

Hope this helps someone in the same situation I was.

I find really useful calling Assembly.GetExecutingAssembly().GetManifestResourceNames();.


    First Unload the project and click on edit the project file. 

    Inside the project file make sure that the item you are fetching from the assembly is included inside <EmbeddedResource> tag.

    Eg: 

         <ItemGroup>
          <EmbeddedResource Include="Template\ForExampleFile.html" />
         </ItemGroup>


    The files I added into the project were just in Content tag but not in the EmbeddedResource as shown below by default. Hence the stream was returning null.
    <ItemGroup>
        <Content Include="Template\ForExampleFile.html" />
  </ItemGroup>

You need to unload your solution.Then edit project.Afterfind your folder and change like this:

<EmbeddedResource Include="yourpath" />

You probably need to specify the path to your txt file in the GetManifestResourceStream parameter, or you could try sticking the txt file in the same directory as your executable. Hope that helps!

참고 URL : https://stackoverflow.com/questions/21637830/getmanifestresourcestream-returns-null

반응형