GetManifestResourceStream returns NULL

前端 未结 13 2701
走了就别回头了
走了就别回头了 2020-11-28 05:41

This is a C# .NET 4.0 application:

I\'m embedding a text file as a resource and then trying to display it in a dialog box:

    var assembly = Assembl         


        
13条回答
  •  生来不讨喜
    2020-11-28 06:07

    A simple and streamlined solution is to have this base class:

    public class EmbededResourceReader
    {
        protected string LoadString(string fileName)
        {
            return LoadString(fileName, Encoding.UTF8);
        }
    
        protected string LoadString(string fileName, Encoding encoding)
        {
            var assembly = this.GetType().Assembly;
            var resourceStream = assembly.GetManifestResourceStream($"{this.GetType().Namespace}.{fileName}");
            using (var reader = new StreamReader(resourceStream, encoding))
            {
                return reader.ReadToEnd();
            }
        }
    }
    

    Then, when you add a resource, you create a reader C# class in the same folder:

    where the reader class MyResource.cs is very simple:

    public class MyResource : EmbededResourceReader
    {
        public string LoadString() => LoadString($"{nameof(MyResource)}.txt");
    }
    

    So, each resource will have a "shadow" class that knows how to read it properly.

    This is how you read the resource in your code:

    var text = new MyResource().LoadString();
    

    And as other answers suggested, do not forget to set "Embedded Resource" in the Build Action property of the resource file.

    The advantage of this uniform solution is

    1. less hassle with finding correct full name of the resource, especially when placed in nested folders
    2. in case when folder is renamed OR Default Namespace in project settings is changed, the code will NOT break

提交回复
热议问题