2016-08-05 66 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

沒問題,請不要忘記接受答案,如果它幫助你;) –