从文本文件读取时值被覆盖

时间:2019-06-26 03:22:05

标签: c#

我正在尝试使用FileStream / StreamReader方法创建一个列表。一切正常,只是每次添加新行时都会重置价格计算。

我认为问题出在保存方法上。我敢肯定这不是由我班上的函数引起的,因为价格显示正确。保存字符串时似乎出现了问题。

这是我的读取方法:

poetry add django

这是我尝试保存字符串的地方...

public static List<Customer> ReadCustomers()
{
    // create an empty customer list
    List<Customer> customerList = new List<Customer>();
    // new Filestream
    FileStream fs = null;
    // new StreamReader
    StreamReader sr = null;
    Customer c; // for reading
    string line;
    string[] fields;
        try
        {
            fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
            sr = new StreamReader(fs);

            while (!sr.EndOfStream)// while there is data
            {
                line = sr.ReadLine();
                fields = line.Split(','); // split sections by commas

                c = new Customer(); // initializes customer object
                c.AccountNo = Convert.ToInt32(fields[0].Trim());
                c.CustomerName = Convert.ToString(fields[1].Trim());
                c.CustomerType = Convert.ToChar(fields[2].Trim());
                c.CustomerCharge = Convert.ToDecimal(fields[3].Trim());
                customerList.Add(c);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally // always execute
        {
            if (fs != null) fs.Close(); // close file
        }
    return customerList;
}

计算:

public static void SaveCustomers(List<Customer> list)
{
    FileStream fs = null;
    StreamWriter sw = null;
    string line;

    try
    {
        fs = new FileStream(path, FileMode.Create, FileAccess.Write);
        sw = new StreamWriter(fs);
        foreach (Customer c in list)     // for each customer in the list
        {
            line = c.AccountNo.ToString() + ", " + c.CustomerName.ToString() + ", " +
                c.CustomerType.ToString() + ", " + c.CustomerCharge.ToString();  // make a line with data
            sw.WriteLine(line);         // and write it to the file
        }
    }
    catch(Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (sw != null) sw.Close(); // stream writer close
        if (fs != null) fs.Close();
    }
}

2 个答案:

答案 0 :(得分:1)

SaveCustomers()中,您确定要打开文件:

fs = new FileStream(path, FileMode.Create, FileAccess.Write);

您可能想要:

fs = new FileStream(path, FileMode.Append, FileAccess.Write);

FileMode.Create将销毁该文件(如果存在)。
FileMode.Append将附加到现有文件中。

也许出于清晰测试的目的,您将输出到另一个文件而不是您读入的文件。

答案 1 :(得分:0)

尝试通过使用append参数来使用它:

 new StreamWriter("c:\\file.txt", true);

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

或者您可以在此处查看相关的答案,这些问题也存在类似的问题

C# add text to text file without rewriting it?