-
December 7th, 2011, 11:09 PM
#1
Beginner problems - reading / writing to a file
Hey, new here, and pretty much new to c#.. Only programming I've done before was Pascal in 6th form, and that was horrendous, but fairly easy.
Anyways, I'm trying to learn c# (it's a module for the course I'm on) by programming things outside of the course.
We haven't got to this section yet, but I need it for the program I'm making..
So anyway, how would I read / write variables to a file, so I can use them later?
Essentially it's a addition program, which counts how much I smoke a day, but obviously I'm gonna have to close the program at some point, thus losing the data I'd put in.
Any ideas? (Sorry if this is a ridiculously basic question).
Oh, and I'm using Visual Studio 2010 (Net 4.0 I believe).
Thanks in advance.
-
December 9th, 2011, 12:56 AM
#2
Re: Beginner problems - reading / writing to a file
The complicated way is with objects and serialization: http://www.switchonthecode.com/tutor...ects-to-a-file
The simple way is to do something like this:
Code:
string someString;
int someInteger;
public void saveData(string savePath)
{
StreamWriter w = new StreamWriter(savePath);
w.WriteLine(someString); //Write the string
w.WriteLine(someInteger); //Write the integer
w.Close();
}
Suppose somestring had text "this is a string!" and someInteger = 5 then this produces a file
with contents
Code:
this is a string!
5
You can read the data back in with a method that looks like this:
Code:
public void loadData(string loadPath)
{
StreamReader r = new StreamReader(loadPath);
//Read in the string
someString = r.ReadLine();
//Read in the integer (as a string) and then parse it to int
someInteger = Int32.Parse(r.ReadLine());
r.Close();
}
If you have other (primitive) types: say you want to save a double, use Double.Parse(double), or for bool, use bool.Parse(bool), etc...
Also make sure you add using System.IO to the top of your file (which is the namespace in which StreamReader and StreamWriter live).
Does that make sense? Let me know if you have more questions.
Best Regards,
BioPhysEngr
http://blog.biophysengr.net
--
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.
-
December 9th, 2011, 05:01 AM
#3
Re: Beginner problems - reading / writing to a file
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
|
Click Here to Expand Forum to Full Width
|