Question

Are there any guides for saving data from a C# application to its own external project file such as embedding images, etc. to be loaded later? Thanks.

Was it helpful?

Solution

You can embed just about any type of data in a .NET assembly and read from it, but you cannot modify your own executable(s), and even if you could, that would be a bad idea. For one, think about how trippy that would be for an antivirus program seeing an EXE suddenly change while running.

If you have metadata (images or any other type of file) you need to read and write, just use the filesystem. The Environment class has functions that will return well-known per application and per-user locations where you can store anything you want.

Edit

I'm not sure if this is what you're asking, but here it goes. Let's say you have a class called Document that contains some text and some images, which are rendered in some unspecified way. So basically it would look like this:

[Serializable]
class Document
{
    public string Text { get; set; }
    public Image[] Images { get; set; }
}

Not sure what Image is, I just made it up. Using the .NET serialization functions you can turn this into a byte stream:

Document doc = GetDocumentFromUI();

MemoryStream stm = new MemoryStream(1024);
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(stm, doc);
byte[] data = stm.ToArray();

Which you can then save to a file. Then you can load the file and turn it into a document:

byte[] data = LoadDocumentFromDisk();

BinaryFormatter fmt = new BinaryFormatter();
MemoryStream stm = new MemoryStream(data);
stm.Position = 0;
Document doc = fmt.Deserialize(stm) as Document;

This is very rough obviously, but you can serialize and deserialize most objects in .NET, including some of the built-in types as well.

OTHER TIPS

It is not possible to do what you want. You can only read embedded resources, not modify them.

Just serialize the data you want to save and deserialize it upon loading. If you want to write more specific data you'll have to determined your own file format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top