Search code examples
c#filestreamstreamwriter

Filestream/Streamwriter not assigning values correctly


I have no experience with Filestream of StreamWriter so I am not sure if there is something obvious that I am missing or not understanding.

I have a method that is using attributes from its current class, and writing them to lines within a file, but it just seems to write blank values to the file.

public void FileWrite()
{
    FileStream fs = new FileStream("test.txt", FileMode.Append, FileAccess.Write);

    StreamWriter sw = new StreamWriter(fs);

    sw.WriteLine("Title = " + title);
    sw.WriteLine("Name = " + fName);
    sw.WriteLine("Last name = " + lName);
    sw.WriteLine("Gender = " + gender);
    sw.WriteLine("Medicare no = " + medicareNo);
    sw.WriteLine("Height = " + height);
    sw.WriteLine("Weight = " + weight);
    sw.WriteLine("Age = " + age);
    sw.WriteLine("Daily Recommended calories = " + cal);
    sw.WriteLine("Ideal Weight = " + idealWeight);

    sw.Flush();
    sw.Close();
    fs.Close();

    Readfile();
}

Any help would be much appreciated as I have not worked with Filestream or StreamWriter in the past.

EDIT:

public class PatientDetails
{
    public void ValuePass()
    {
        FileHandler file = new FileHandler();

        file.setTitle(this.title);
        file.setName(this.fName, this.lName);
        file.setMedicare(this.medicareNo);
        file.setGender(this.gender);
        file.setMeasurements(this.weight, this.height, this.age);
        file.setCalcs(this.cal, this.idealWeight);

        Console.WriteLine(this.fName + this.lName);
    }
}

This is how the values are passed from within a different class.

And the values are obtained from user input:

do
{
    Console.WriteLine("\nPlease enter the Title");
    this.title = Console.ReadLine();

Solution

  • you can do as below

    FileHandler fh = new FileHandler();
    fh.setTitle("New Title"); // set all the values.....
    fh.FileWrite();