C# Program to Write an Array to a File



Use WriteAllLines method to write an array to a file.

Firstly, set a string array −

string[] stringArray = new string[] {
   "one",
   "two",
   "three"
};

Now, use the WriteAllLines method to add the above array to a file −

File.WriteAllLines("new.txt", stringArray);

Here is the complete code −

Example

 Live Demo

using System.IO;
using System;
public class Program {
   public static void Main() {
      string[] stringArray = new string[] {
         "one",
         "two",
         "three"
      };
      File.WriteAllLines("new.txt", stringArray);
      using (StreamReader sr = new StreamReader("new.txt")) {
         string res = sr.ReadToEnd();
         Console.WriteLine(res);
      }
   }
}

Output

one
two
three
Updated on: 2020-06-22T14:36:30+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements