C# Program to write an array to a file

CsharpProgrammingServer Side Programming

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
raja
Published on 05-Sep-2018 07:49:52
Advertisements