2016-08-05 72 views
0

我正在制作一个应用程序,它将保存和加载产品。这些产品具有产品名称,客户名称和固件位置三个属性。但是,当我试图保存它们时,它只会保存一个,并保留最近保存的产品。以下是我的产品分类代码:保存不断覆盖本身C#

public class Product 
{ 

    //private product data 
    private string productName; 

    public string getProductName() 
    { 
     return this.productName; 
    } 

    public void setProductName (string inProductName) 
    { 
     this.productName = inProductName; 
    } 

    private string customerName; 

    public string getCustomerName() 
    { 
     return this.customerName; 
    } 

    public void setCustomerName (string inCustomerName) 
    { 
     this.customerName = inCustomerName; 
    } 

    private string firmwareLocation; 

    public string getFirmwareLocation() 
    { 
     return this.firmwareLocation; 
    } 

    public void setFirmwareLocation (string inFirmwareLocation) 
    { 
     this.firmwareLocation = inFirmwareLocation; 
    } 


    //constructor 
    public Product (string inProductName, string inCustomerName, string inFirmwareLocation) 
    { 
     productName = inProductName; 
     customerName = inCustomerName; 
     firmwareLocation = inFirmwareLocation; 
    } 


    //save method 
    public void Save (System.IO.TextWriter textOut) 
    { 
     textOut.WriteLine(productName); 
     textOut.WriteLine(customerName); 
     textOut.WriteLine(firmwareLocation); 
    } 

    public bool Save (string filename) 
    { 
     System.IO.TextWriter textOut = null; 
     try 
     { 
      textOut = new System.IO.StreamWriter(filename); 
      Save(textOut); 
     } 
     catch 
     { 
      return false; 
     } 
     finally 
     { 
      if (textOut != null) 
      { 
       textOut.Close(); 
      } 
     } 
     return true; 
    } 

最后是我的保存方法。

下面是当用户按下附加产品按钮的代码:

private void Add_Click(object sender, RoutedEventArgs e) 
    { 
     //get input from user 
     string inputCustomerName = customerNameTextBox.Text; 
     string inputProductName = productNameTextBox.Text; 
     string inputFirmwareLocation = firmwareTextBox.Text; 

     try 
     { 
      Product newProduct = new Product(inputProductName, inputCustomerName, inputFirmwareLocation); 
      newProduct.Save("products.txt"); 
      MessageBox.Show("Product added"); 
     } 
     catch 
     { 
      MessageBox.Show("Product could not be added"); 
     } 
    } 
+0

是的,它会因为你不附加到你刚刚写在顶部的文件 – BugFinder

回答

2

你没有追加文本到您的文件,这就是为什么它保持了一遍又一遍覆盖的最后一项。

试图改变自己的保存方法:

public bool Save (string filename) 
    { 
     System.IO.TextWriter textOut = null; 
     try 
     { 
      textOut = new System.IO.StreamWriter(filename, true); 
      Save(textOut); 
     } 
     catch 
     { 
      return false; 
     } 
     finally 
     { 
      if (textOut != null) 
      { 
       textOut.Close(); 
      } 
     } 
     return true; 
    } 

通知“真实”作为StreamWriter的构造函数的第二个参数。这告诉StreamWriter追加新行。

+0

完美的作品谢谢 – lucycopp

+0

没问题,请不要忘记接受答案,如果它帮助你;) –