|
-
Catfish
Saving data in a C# program
I am writing a program that will require saving/backing up data. I have programmed in C++ for a while but I am somewhat new to C#. Is there a way I can back up the whole state of the program, like write the contents of memory to a file on the hard drive? I know I could write each variable to a text file but I thought there might be an easier way to do it.
Thanks
-
Hammerhead Shark
i dont know about the whole program (but im pretty sure this can work with that) but what you want to look up is C# serialization. this allows sthe saving of class instances for persistence.
here are some links to start you on yer way
http://www.andymcm.com/dotnetfaq.htm
www.dotnetjohn.com/articles.aspx?articleid=173
Last edited by nattylife; 06-14-2005 at 02:24 PM.
-
NullPointerException
One cool thing I've been doing recently in .NET applications is to write to something called "isolated storage" which is really a directory that lives under the Application Data directory of your user profile.
It's nice because neither you nor the user need to know anything about the files or the location, and it's unique for each user.
For example, I'd like to store some default options in a program I just wrote. Just 3 strings that fill in some boxes when it starts. I just grab these out of IsolatedStorage (of course, the first time it's run, you need to check for an empty/new file and create it).
Here's a code snippet for reading from and writing to IsolatedStorage:
Code:
/// <summary>
/// Read saved options from isolated storage.
/// </summary>
private void GetOptions() {
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("options.txt", FileMode.OpenOrCreate);
StreamReader reader = new StreamReader(stream);
String line = reader.ReadLine();
if (line != null) {
dpath = line;
bpath = reader.ReadLine();
ipath = reader.ReadLine();
reader.Close();
stream.Close();
}
else {
dpath = "c:\\";
bpath = "\"C:\\Program Files\\Opera7\\opera.exe\"";
ipath = "save\\";
reader.Close();
stream.Close();
SetOptions();
}
}
/// <summary>
/// Write options to isolated storage.
/// </summary>
private void SetOptions() {
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("options.txt", FileMode.Create);
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(dpath);
writer.WriteLine(bpath);
writer.WriteLine(ipath);
writer.Flush();
writer.Close();
stream.Close();
}
Clearly, you're not going to store the entire state of the program like this, but it could be a simple way of doing what you need. Of course, you could serialize various objects and store them in IsolatedStorage too.
Open Source is free like a puppy is free.
It's only when you look at an ant through a magnifying glass on a sunny day that you realise how often they burst into flames.
Understanding Evolution
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|