Create file in C#

Create file in C# using File.Create Method
  • 4739
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. 

// Full file name 
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());
}   

The Create method has four overloaded forms provide options with a file buffer size, file options, and file security.

© 2020 DotNetHeaven. All rights reserved.