Embedded resource in .Net Core libraries

前端 未结 5 622
醉梦人生
醉梦人生 2020-12-24 10:05

I just have started looking into .Net Core, and I don\'t see classical resources and anything what looks like resources. In classical .Net class libraries I was able to add,

5条回答
  •  自闭症患者
    2020-12-24 10:43

    People have already generally answered this, so this is a rendering of the answers into something simple.

    Before using the following, the file should be added as an embedded resource to the .csproj / project.json

    Usage

    var myJsonFile = ReadManifestData("myJsonFile.json");
    
    1. Parameter: embedded filename name; Type: any class from the target resource's assembly
    2. looks for an embedded resource with that name
    3. returns the string value

    Method

    public static string ReadManifestData(string embeddedFileName) where TSource : class
    {
        var assembly = typeof(TSource).GetTypeInfo().Assembly;
        var resourceName = assembly.GetManifestResourceNames().First(s => s.EndsWith(embeddedFileName,StringComparison.CurrentCultureIgnoreCase));
    
        using (var stream = assembly.GetManifestResourceStream(resourceName))
        {
            if (stream == null)
            {
                throw new InvalidOperationException("Could not load manifest resource stream.");
            }
            using (var reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
    }
    

提交回复
热议问题