top of page

C Sharp

Public·2 members

Create a Text File in C#

Create a Text File in C#

The following 4 methods can be used to create a text file in C#. In this article and code sample, we will learn how to use these methods to create text files.

File.Create File.CreateText FileInfo.Create FileInfo.CreateText

File.Create Method

The File.Create() method takes a file name with the full path as its first and required parameter and creates a file at the specified location. If same file already exists at the same location, this method overwrites the file.

The following code snippet creates a file Mahesh.txt in C:\Temp folder. If file already exists, the code will delete the existing file. The code writes two arrays of bytes to the file.

The Create method creates and returns a FileStream object that is responsible for reading and writing the specified file.



 string fileName = @"C:\Temp\Mahesh.txt";  
    try
   {    
   // Check if file already exists. If yes, delete it.          if (File.Exists(fileName))     
      {           
    File.Delete(fileName);   
        }  
       // Create a new file     using (FileStream fs = File.Create(fileName))  
          {     
   // Add some text to file         Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");              fs.Write(title, 0, title.Length);           byte[] author = new UTF8Encoding(true).GetBytes("Mahesh Chand"); 
          fs.Write(author, 0, author.Length);   
        } 
        // Open the stream and read it back.    using (StreamReader sr = File.OpenText(fileName))     
      {    
    string s = "";   
      while ((s = sr.ReadLine()) != null)      
          {    
                Console.WriteLine(s);      
          }     
       }   
     }    
    catch (Exception Ex)  
      {  
          Console.WriteLine(Ex.ToString());   
     } 

73 Views
bottom of page