C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# File Class: File Operations

The File class in C# is part of the System.IO namespace and provides methods to create, read, update, and delete files. In this tutorial, we'll go over some common file operations using the File class.

Before using the File class, make sure to include the following directive at the top of your file:

using System.IO;
  • Creating a file:

To create a new file or overwrite an existing one, use the File.Create method:

string fileName = "example.txt";
using (FileStream fileStream = File.Create(fileName))
{
    // Do something with the file stream, e.g., write data to the file
}
  • Writing text to a file:

To write text to a file, use the File.WriteAllText method. This method creates a new file, writes the specified string to the file, and then closes the file:

string content = "Hello, World!";
string fileName = "example.txt";

File.WriteAllText(fileName, content);
  • Appending text to a file:

To append text to an existing file, use the File.AppendAllText method:

string content = "This is an appended line.";
string fileName = "example.txt";

File.AppendAllText(fileName, content);
  • Reading text from a file:

To read the contents of a file as a string, use the File.ReadAllText method:

string fileName = "example.txt";
string content = File.ReadAllText(fileName);

Console.WriteLine("File content:");
Console.WriteLine(content);
  • Checking if a file exists:

To check if a file exists, use the File.Exists method:

string fileName = "example.txt";

if (File.Exists(fileName))
{
    Console.WriteLine("The file exists.");
}
else
{
    Console.WriteLine("The file does not exist.");
}
  • Deleting a file:

To delete a file, use the File.Delete method:

string fileName = "example.txt";

if (File.Exists(fileName))
{
    File.Delete(fileName);
    Console.WriteLine("File deleted.");
}
else
{
    Console.WriteLine("The file does not exist.");
}
  • Moving or renaming a file:

To move a file to a new location or rename it, use the File.Move method:

string sourceFileName = "example.txt";
string destinationFileName = "example_renamed.txt";

File.Move(sourceFileName, destinationFileName);

In this tutorial, we've covered some common file operations using the File class in C#. By using the methods provided by the File class, you can easily create, read, update, and delete files in your C# applications.

  1. Working with files using C#:

    • Description: C# provides the File class in the System.IO namespace to perform various file-related operations.
    • Code:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main()
          {
              string filePath = "example.txt";
      
              // Check if the file exists
              if (File.Exists(filePath))
              {
                  // Perform file operations
                  Console.WriteLine($"File '{filePath}' exists!");
              }
              else
              {
                  Console.WriteLine($"File '{filePath}' does not exist.");
              }
          }
      }
      
  2. Reading and writing files in C#:

    • Description: Use File.ReadAllText and File.WriteAllText for simple text file reading and writing.
    • Code:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main()
          {
              string filePath = "example.txt";
      
              // Writing to a file
              File.WriteAllText(filePath, "Hello, World!");
      
              // Reading from a file
              string content = File.ReadAllText(filePath);
              Console.WriteLine($"File content: {content}");
          }
      }
      
  3. Appending to a file in C#:

    • Description: Use File.AppendAllText to append content to an existing file.
    • Code:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main()
          {
              string filePath = "example.txt";
      
              // Append to a file
              File.AppendAllText(filePath, "\nAppended content.");
      
              // Reading from the file after appending
              string content = File.ReadAllText(filePath);
              Console.WriteLine($"File content after appending: {content}");
          }
      }
      
  4. Deleting files in C#:

    • Description: Use File.Delete to delete a file.
    • Code:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main()
          {
              string filePath = "example.txt";
      
              // Delete the file
              File.Delete(filePath);
      
              Console.WriteLine($"File '{filePath}' deleted.");
          }
      }
      
  5. Renaming files with C# File class:

    • Description: Use File.Move to rename or move a file.
    • Code:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main()
          {
              string oldFilePath = "old.txt";
              string newFilePath = "new.txt";
      
              // Rename the file
              File.Move(oldFilePath, newFilePath);
      
              Console.WriteLine($"File renamed from '{oldFilePath}' to '{newFilePath}'.");
          }
      }
      
  6. C# File attributes:

    • Description: The File class allows you to retrieve and modify file attributes.
    • Code:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main()
          {
              string filePath = "example.txt";
      
              // Get file attributes
              FileAttributes attributes = File.GetAttributes(filePath);
      
              // Check if a file is read-only
              if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
              {
                  Console.WriteLine($"File '{filePath}' is read-only.");
              }
          }
      }
      
  7. File security and permissions in C#:

    • Description: Use the FileSecurity class to manage file access control and permissions.
    • Code:
      using System;
      using System.IO;
      using System.Security.AccessControl;
      
      class Program
      {
          static void Main()
          {
              string filePath = "example.txt";
      
              // Get or create file security
              FileSecurity fileSecurity = File.GetAccessControl(filePath) ?? new FileSecurity();
      
              // Add or modify permissions
              fileSecurity.AddAccessRule(new FileSystemAccessRule("user", FileSystemRights.Read, AccessControlType.Allow));
      
              // Apply file security
              File.SetAccessControl(filePath, fileSecurity);
      
              Console.WriteLine($"File security updated for '{filePath}'.");
          }
      }
      
  8. C# FileStream vs File class:

    • Description: Both FileStream and File class are used for file operations, but FileStream provides more control over low-level file I/O.
    • Code: Example for using FileStream:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main()
          {
              string filePath = "example.txt";
      
              // Using FileStream for reading and writing
              using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
              {
                  // Perform read and write operations with FileStream
                  // ...
              }
          }
      }