C# program to write text to a file

C# | Write text to a file: In this tutorial, we will learn how to write text to a file using C# program? Submitted by IncludeHelp, on October 28, 2017 [Last updated : March 23, 2023]

Writing text to a file in C#

To write text to a file in C#, we can use File.WriteAllText() function, which is used to write all text (passed as an argument) in a file. Note: If the file does not exist at the specified location, this method creates the file first and then writes all text to the file.

Syntax:

void File.WriteAllText(path, content);

Where, path is the filename with it's location and content is the text to be written to the file.

C# program to write text to a file

using System;

//We need to include this namespace 
// for file handling
using System.IO;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      string s;

      Console.WriteLine("Enter text to Write into File : ");
      s = Console.ReadLine();

      File.WriteAllText("ABC.TXT", s);
      Console.WriteLine("\nFile Creation Done");
    }
  }
}

Output

Enter text to Write into File :
Hello , This is a sample program for writing text into file.

File Creation Done

Explanation

In above program, we need to remember, when we use "File" class, System.IO namespace must be included in the program.

C# File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.