C# File Class

The File class in the .NET Framework class library provides static methods for creating, reading, copying, moving, and deleting files. In this article, we will see how to create a text file using different options available in .NET.

Create a File

We can create a file in four different following methods

  • File.Create
  •  
  • File.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.

// 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.

Create File with Buffer Size

File.Create(name of the file, number of bytes buffered for read and write to the file)

FileStream fs = File.Create(fileName, 1024);

Create File with File Options

The File.Create method takes third parameters as a FileOptions enumeration that can be used to specify advanced options for creating a FileStream object.

FileStream fs = File.Create(fileName, 1024, FileOptions.WriteThrough);

The following values

  • None - Default value. No additional options.

  • WriteThrough - Indicates that the system should write through any intermediate cache and go directly to disk.

  • Asynchronous - Indicates that a file can be used for asynchronous reading and writing.

  • RandomAccess - Indicates that the file is accessed randomly. The system can use this as a hint to optimize file caching.

  • DeleteOnClose - Indicates that a file is automatically deleted when it is no longer in use.
    SequentialScan - Indicates that the file is to be accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur; however, correct operation is still guaranteed. Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes.

  • Encrypted - Indicates that a file is encrypted and can be decrypted only by using the same user account used for encryption.

Create File with File Security

The Create method also has an option to specify the file security options. The fourth parameter passed within the Create method of type FileSecurity object. The FileSecurity object has properties to set

try
{
    string fileName = @"C:\Temp\Mahesh2.txt";
   
// Create File Security
    FileSecurity fSecurity = new FileSecurity();
    fSecurity.AddAccessRule(new FileSystemAccessRule(@"DomainName\AccountName", FileSystemRights.ReadData, AccessControlType.Allow));

    using (FileStream fs = File.Create(fileName, 1024, FileOptions.WriteThrough, fSecurity))
    {
       
// 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);
    }
    Console.WriteLine("Adding access control entry for " + fileName); 
    Console.WriteLine("Done.");
}

catch
(Exception e)
{
   Console.WriteLine(e);

}

Up Next
    Ebook Download
    View all
    Learn
    View all