Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# precompile a large array or other solution to embed large data in executable

Tags:

c#

I have to fill a excel file in my app, open, write and close.

The problem is that file contains a lot of format and macros (is a company template) and I realized that will be extremely hard to re-generate from C# and most important, to maintain.

So I opened excel template with a hexeditor, took all bytes as array like this

namespace myapp
{

    public static class ReviewTemplate // exported with HXD
    {
        public static string name = "AS-04522-EN";
        public static byte[] rawData = {
    0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x3E, 0x00, 0x03, 0x00, 0xFE, 0xFF, 0x09, 0x00, 0x06, 0x00, 0x00, 0x00,
...
...
...
}
}

Then, generate from C# like this

File.WriteAllBytes(ReviewTemplate.name + DateTime.Now.ToString("_dd_MM_yyyy_HH_mm_ss") + ".xls", ReviewTemplate.rawData);

It works wonderful except that all array file (*.cs) has 15MB and when I double click any function name in C# for refactor or something, the .NET hangs several minutes.

So the big question is, how can I pre-compile somehow this array.cs file so .NET use as it is? Perhaps put all in some dll? In C I's use the *.obj file.

EDITED

To be more clear, after I generate the required excel (that have 2.5MB anyhow) i use interop to open, write then close.

Is it possible to embed all this data and write somehow in memory, then save finally as excel file on disk?

Thanks,

like image 285
orfruit Avatar asked May 07 '26 22:05

orfruit


1 Answers

If you want the template to be inside your .exe/dll, add the .xls to your C# project, right click, properties, set build action to “Embedded resource”.

When you’ll need to fill it, call Assembly.GetManifestResourceStream to open the stream of that embedded resource, then use CopyTo instead of WriteAllBytes.

Update: example (untested)

Stream source = Assembly.GetExecutingAssembly().GetManifestResourceStream( ... );
string destName = "AS-04522-EN" + DateTime.Now.ToString("_dd_MM_yyyy_HH_mm_ss") + ".xls";
using( Stream dest = File.Create( destName ) )
    source.CopyTo( dest );
like image 181
Soonts Avatar answered May 10 '26 12:05

Soonts