簡體   English   中英

如何將文本附加到我的文件中,以便添加新內容而不是覆蓋

[英]How to append text to my file so it adds new content instead of overwrite

一切正常,直到我注冊一個新用戶並單擊“保存”,它會用新信息覆蓋文本文件中的內容,我想添加新行並再次開始添加內容數組。 我知道有一個“附加”功能,但是我嘗試了很多事情,但似乎無法使其與我當前的寫入文件方式一起使用。

    private async void button1_Click(object sender, EventArgs e)
    {
       string[] contents = new string[4];
    contents[0] = "Name: " + txtName.Text;
    contents[1] = "Address: " + txtAddress.Text;
    contents[2] = "Phone: " + txtPhone.Text;
    contents[3] = "Blood Type: " + cmbBloodType.SelectedItem.ToString();

    System.IO.File.WriteAllLines( @"C:\Users\Ben\Documents\C#\Final\Bloodbank\BloodBank\bin\Debug\Bloodbank.txt", contents);

    }

您是否嘗試過File.AppendAllText() 這是一個例子:

File.AppendAllText(@"C:\Users\Ben\Documents\C#\Final\Bloodbank\BloodBank\bin\Debug\Bloodbank.txt", "content" + Environment.NewLine);

我認為這是因為您的內容是一個數組,所以您必須將這個數組連接到一個字符串中,例如:

    System.IO.File.AppendAllText(@"C:\Users\Ben\Documents\C#\Final\Bloodbank\BloodBank\bin\Debug\Bloodbank.txt", string.Join(Environment.NewLine, contents));

編輯代碼:當您保存文件時,請嘗試:

private async void button1_Click(object sender, EventArgs e)
{
    System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
    stringBuilder.AppendLine("Name: " + txtName.Text);
    stringBuilder.AppendLine("Address: " + txtAddress.Text);
    stringBuilder.AppendLine("Phone: " + txtPhone.Text);
    stringBuilder.AppendLine("Blood Type: " + cmbBloodType.SelectedItem.ToString());

    System.IO.File.AppendAllText(@"C:\Users\Ben\Documents\C#\Final\Bloodbank\BloodBank\bin\Debug\Bloodbank.txt", stringBuilder.ToString() + Environment.NewLine);
}

那應該將文本追加到文件末尾。 官方文檔可以在這里找到: https : //msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM