Search code examples
c#.netembedded-resourcedotnetzip

Is it possible to embed binary data in a .NET assembly


Is it possible to embed binary data (as a resource, or by some other mean) in the C# assembly and then read the binary data from assembly during run-time and write it as a file.

I am making a DRM application and purpose is that the data must be hidden in the assembly as embedded resource, or a password protected ZIP file. So, I will try to embed the resource and if not possible then will look for a ZIP / UN-ZIP library with password protection to save DRM data.

I am writing a program in C# in which should have a binary data and it is added in the assembly during compile just like images, icons are added in assembly when we compile, and then when the assembly is executed by user then the binary data is read and saved as an external file.

Is it possible? then how to do it?


Solution

  • Yes. If you are using resources, you can include files too, which are represented as a byte array. Else you can include a file and set the Build Action to Embedded Resource, which include it as a resource too, which you can manually read.

    public byte[] ExtractResource(Assembly assembly, string resourceName)
    {
        if (assembly == null)
        {
            return null;
        }
    
        using (Stream resFilestream = assembly.GetManifestResourceStream(resourceName))
        {
            if (resFilestream == null)
            {
                return null;
            }
    
            byte[] bytes = new byte[resFilestream.Length];
            resFilestream.Read(bytes, 0, bytes.Length);
    
            return bytes;
        }
    }
    

    Then use it like this:

    byte[] bytes = this.ExtractResource( Assembly.GetExecutingAssembly()
                                       , "Project.Namespace.NameOfFile.ext"
                                       );