簡體   English   中英

使用C#在文本文件中發送數組的內容

[英]Send the content of an Array in a text file in C#

我正在c#中創建一個小程序,它允許您將數字數組的內容發送到文本文件。 但是當我打開文本文件時,它僅顯示數組的最后一個元素(10)。 我如何確保他發送文本文件中的所有數字,而不僅僅是最后一個數字。

int[] Numbers = { 1, 2, 4, 5, 6, 7, 8, 9, 10 };
        string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        foreach (var x in Numbers)
        {
            File.WriteAllText(path + @"\" + "numbers.txt", x .ToString () + "\r\n";
        }

您可以使用string.Join並擺脫foreach

 File.WriteAllText(path + @"\numbers.txt", string.Join(Environment.NewLine, Numbers));

或者,您可以使用foreach循環,但更改為AppendAllText而不是WriteAllText

foreach (var x in Numbers)
{
    File.AppendAllText(path + @"\numbers.txt", x.ToString() + "\r\n");
}

WriteAllText將替換文件中的所有文本,而AppendAllText將追加到文件中。 在您的示例中, WriteAllText會覆蓋先前的值,因此最終只能得到文件中的最后一個值。

暫無
暫無

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

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