Filestream / Streamwriter未正确分配值

时间:2013-09-15 06:35:39

标签: c# filestream streamwriter

我对StreamWriter的文件流没有任何经验,所以我不确定是否有一些我遗漏或不理解的东西。

我有一个方法,它使用当前类的属性,并将它们写入文件中的行,但它似乎只是将空白值写入文件。

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();
}

我很感激任何帮助,因为我过去没有使用过Filestream或StreamWriter。

编辑:

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);
    }
}

这是从不同类中传递值的方式。

这些值来自用户输入:

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

2 个答案:

答案 0 :(得分:0)

你可以这样做

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

答案 1 :(得分:0)

FileWrite()函数中的代码是正确无误的。您应首先检查PatientDetail类的属性是否具有值。如果有,则file.setTitle()必须按如下方式实施:

file.setTitle(string text)
{
title = text; //title is the attribute of `FileHanlder` class 
}

另请致电file.FileWrite()函数中的ValuePass()