C# Program to Create File and Write to the File


Introduction

Creating a file and writing in it is the basics of file handling. Here, we are going to discuss a way to write a C# program to create the file and write to the file. File handling or file management in layman's terms the various processes such as making the file, reading from it, writing to it, appending it, and so on. The viewing and writing of files are the two most common operations in file management.

Input and output happen due to the streams which provide a generic view of a sequence of bytes. Stream is an abstract class. It is the gateway for the different processes i.e., input and output. In C# file handling file stream is used. Now. let us discuss the different ways to create the file and write the file.

1. File.WriteAllText() method

This is one of the most used methods and one of the simplest to use. This method creates a file with the programmer-defined name and writes the data from the string input. After the data input is completed the file is closed. If the file that the user wants to create exists then the previous file from the storage is overridden.

public static void WriteAllText (string path, string? contents); 

Both the input parameters are strings. This uses UTF-8 encoding by default without a BOM i.e., Byte-Order Mark. If the user wants to use a different encoding then the user can pass an additional third parameter for that specific encoding.

Algorithm

Now, let us discuss the algorithm to create the file and write the file by using File.WriteAllText() method.

Step 1 − The variable is declared with the text file name.

Step 2  The string is declared with the data.

Step 3  The information is input into the file and stored in it.

Step 4  After the information is written a success message is printed.

Example

using System.Text;
using System;
using System.IO;
class testfiles {
   public static void Main(){
      var loc = "tutpoint.txt";
      string inform = "Tutorials Point";
      File.WriteAllText(loc, inform);
      
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
} 

Output

Text input completed. 

2. File.WriteAllLines() method

This method creates a file with the programmer-defined name and writes a single string input or multiple strings at one go. After the data input is completed the file is closed. If the file that the user wants to create exists then the previous file from the storage is overridden.

public static void WriteAllLines (string path, string[] contents); 

This uses UTF-8 encoding without a BOM i.e., Byte-Order Mark.

Algorithm

This algorithm is about File.WriteAllLines().

Step 1 − The variable is declared with the text file name.

Step 2  The string is declared with the data.

Step 3  Data is written in the tutpoint.txt file.

Step 4  Write a code line to display successful work done.

Example

using System.Text;
using System;
using System.IO;
class testfiles {
   public static void Main(){
      var loc = "tutpoint.txt";
      string[] inform = {"Tutorials", "Point", "learn"};
      File.WriteAllLines(loc, inform);
      
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
}

Output

Text input completed. 

3. File.WriteAllBytes() method

What if want to do a byte array entry? Well, then we can use File.WriteAllByttes() method. This method creates a file with the programmer-defined name. Data of the byte array is written in the file and the file is closed. If the file that the user wants to create exists then the previous file from the storage is overridden.

public static void WriteAllBytes (string path, byte[] bytes); 

Algorithm

Now, let us discuss the algorithm to create the file and write the file by using File.WriteAllBytes() method.

Step 1 − The variable is declared with the text file name.

Step 2  The string is declared with the data.

Step 3  The information is input into the file and stored in it.

Step 4  After the information is written a success message is printed.

Example

using System.Text;
using System;
using System.IO;
class testfiles {
   public static void Main(){
      var loc = "tutpoint.txt";
      string inform = "Tutorial point contains a plethora of technical articles";
      byte[] details = Encoding.ASCII.GetBytes(inform);
      File.WriteAllBytes(loc, details);
      
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
} 

Output

Text input completed. 

4. Asynchronous method

If the user wants the entry of data asynchronously rather than synchronously then c# also offers that to the user. All the methods that we have discussed above can also be used asynchronously. Here, we will discuss one of them and the rest can be implemented similarly.

We will see about WriteAllTextAsync().

public static System.Threading.Tasks.Task WriteAllTextAsync (string path, string? contents, System.Threading.CancellationToken cancellationToken = default);

This method creates a file asynchronously and then writes all the text in the file. After that, the file is closed.

Algorithm

Now, let us discuss the algorithm to create the file and write the file by using File.WriteAllTextAsync() method.

Step 1 − The variable is declared with the text file name.

Step 2  The string is declared with the data.

Step 3  The information is input into the file and stored in it.

Step 4  After the information is written a success message is printed.

Example

using System.Text;
using System;
using System.IO;
using System.Threading.Tasks;
class testfiles {
   public static void Main() {
      var loc = "tutpoint.txt";
      string inform = "falcon";
       
      // await File.WriteAllTextAsync(loc, inform);
      Task asyncTask = WriteFileAsync(loc, inform);
        
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
   static async Task WriteFileAsync(string loc, string inform){
      Console.WriteLine("Async Write File has started.");
      using(StreamWriter outputFile = new StreamWriter(Path.Combine(loc)) ){
         await outputFile.WriteAsync(inform);
      }
      Console.WriteLine("Stage 2");
   }
} 

Output

Async Write File has started.
stage 2
Text input completed.

Conclusion

So, with this comes the end of the article. In this article, we have learned a C# program to create the file and write to the file. We learned the various method to do so. We also discussed the different algorithms that do so and learned their codes. We hope that this article enhances your knowledge regarding C#.

Updated on: 31-Mar-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements