I'm creating a little program in c# that allows you to send the content of an array of numbers to a text file. But when I open the text file, it only show the last element of the array (10). How can I make sure that he sends all the numbers in the text file and not only the last number.
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";
}
You could use string.Join
and get rid of the foreach
:
File.WriteAllText(path + @"\numbers.txt", string.Join(Environment.NewLine, Numbers));
Or you could use the foreach
loop but change to AppendAllText
instead of WriteAllText
:
foreach (var x in Numbers)
{
File.AppendAllText(path + @"\numbers.txt", x.ToString() + "\r\n");
}
WriteAllText
will replace all the text in a file while AppendAllText
will append to the file. In your example WriteAllText
is overwriting the previous value(s) so you only end up with the last value in the file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.