How To Get A Stream Object From A Resource File (Console App/Windows Service Project)

拟墨画扇 提交于 2019-11-29 09:59:57
Andrew

If you set the files in the Resources folder to Embedded Resource then you should have seen it listed in the GetManifestResourceNames() call. You could try

var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MicroSecurity.EmailService.Resources.logo.jpg");

The name should be "MicroSecurity.EmailService.Resources.logo.jpg" if it is in the Resources folder. However, marking the file itself as an Embedded Resource defeats the purpose of the Resources file (the image itself would be embedded twice).

You can remove the resources file entirely and set each file as an Embedded Resource. At that point, there should be separate manifest resources for each file. In a C# project, each file name will be prefixed by the project namespace + the sub folder. Eg. if you add a "logo.jpg" file in a Resources/Embedded folder, the resource name will be "MicroSecurity.EmailService.Resources.Embedded.logo.jpg".

Alternatively, get the bitmap from the Resources file and convert it to a stream. You can find an example of converting a Bitmap to a MemoryStream in How do I convert a Bitmap to byte[]?

Can you use:

System.Drawing.Bitmap myLogo = MicroSecurity.Properties.Resources.logo;
Tin Nguyen
public static readonly Func<string, object> GetDataByType = (path) => {
    var fromStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path);
    var formatter = new BinaryFormatter();

    if (fromStream != null) {
        var obj = formatter.Deserialize(fromStream);
        fromStream.Close();
        return obj;
    }

    return null;
};


var test GetDataByType("Resources.logo");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!