How to get resources embedded in another project

前端 未结 2 1406
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 18:19

Let us say I have a C# class library project, which only contains xml files as embedded resources. I would like to access these resources from another solution project. As t

相关标签:
2条回答
  • 2020-12-15 18:43

    Here is an approach I find works pretty well when I don't want loose files in the project. It can be applied to any assembly.

    In the following example there is a folder in the root of the project called 'MyDocuments' and a file called 'Document.pdf' inside of that. The document is marked as an Embedded resource.

    You can access the resource like this, building out the namespace first before calling GetManifestResourceStream():

    Assembly assembly = Assembly.GetExecutingAssembly();
    string ns = typeof(Program).Namespace;
    string name = String.Format("{0}.MyDocuments.Document.pdf", ns);
    using (var stream = assembly.GetManifestResourceStream(name))
    {
        if (stream == null) return null;
        byte[] buffer = new byte[stream.Length];
        stream.Read(buffer, 0, buffer.Length);
        return buffer;
    }
    

    The only issue I have found is when the name space contains numbers after a '.' (e.g. MyDocuments.462). When a namespace is a number the compiler will prepend an underscore (so MyDocuments.462 becomes MyDocuments._462).

    0 讨论(0)
  • 2020-12-15 18:45

    you can use Assembly.GetManifestResourceStream() to load the xml file from the embedded assembly.

    System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("ActivityListItemData.xml"); 
    

    EDIT

    You can use Assembly.Load() and load the target assembly and read the resource from there.

    Assembly.LoadFrom("Embedded Assembly Path").GetManifestResourceStream("ActivityListItemData.xml");
    
    0 讨论(0)
提交回复
热议问题