C# File

By FoxLearn 12/13/2024 1:37:26 PM   196
In C#, to work with files, you use the System.IO and System.Text namespaces.

The File class in the System.IO namespace provides static methods for various file operations, including creating, copying, deleting, moving, and opening files. It also facilitates the creation of FileStream objects for reading from or writing to files.

C# File.Create

The File.Create method creates a new file or overwrites an existing file at the specified path. It returns a FileStream that provides read/write access to the file.

static void Main(string[] args)
{
    string filePath = @"C:\sample.txt";

    // Create or overwrite the file
    using (FileStream fs = File.Create(filePath))
    {
        // Optionally, write data to the file
        byte[] data = new byte[] { 65, 66, 67 };  // ASCII codes for 'A', 'B', 'C'
        fs.Write(data, 0, data.Length);
    }
}

C# File.CreateText

The File.CreateText method creates a new file or opens an existing file for writing UTF-8 encoded text. If the file already exists, its contents are overwritten. It returns a StreamWriter that writes to the file using UTF-8 encoding.

var path = "c:\\sample.txt";
using StreamWriter sw = File.CreateText(path);
sw.WriteLine("c#");
sw.WriteLine("foxlearn");
sw.WriteLine("programming");

The example uses File.CreateText to create a new file and then writes three words to it using the WriteLine method. Each word is written on a new line in the file.

C# File.Copy

The File.Copy method copies an existing file to a new location. It takes two parameters: the source file and the destination file.

var sourcePath = "c:\sample1.txt";
var destPath = "c:\sample2.txt";
File.Copy(sourcePath, destPath);

C# File.Move

The File.Move method moves a specified file to a new location. It can be used to either move a file to a different directory or to rename the file.

var sourcePath = "c:\sample.txt";
var destPath = "c:\data.txt";

File.Move(sourcePath, destPath);

The example renames sample.txt to data.txt.

C# File.Exists

The File.Exists method determines whether the specified file exists at the given path. It returns true if the file exists, and false otherwise.

var path = "c:\sample.txt";

if (File.Exists(path))
{
    // file exists
} else {
    // file does not exist
}

C# File.Delete

The File.Delete method deletes the specified file. If the file does not exist, an exception is thrown.

var path = "c:\sample.txt";
File.Delete(path);

C# File.GetCreationTime

The File.GetCreationTime method returns the creation date and time of the specified file or directory.

var path = "c:\sample.txt";
DateTime dt = File.GetCreationTime(path);
Console.WriteLine($"Creation time: {dt}");

The example prints the creation date and time of the sample.txt file using the File.GetCreationTime method.

C# File.GetLastWriteTime

The File.GetLastWriteTime method returns the date and time when the specified file or directory was last modified or written to.

var path = "c:\sample.txt";
DateTime dt = File.GetLastWriteTime(path);
Console.WriteLine($"Last write time: {dt}");

C# File.Open

The File.Open method in C# opens a FileStream at the specified path. Its overloaded versions allow you to specify the file mode (such as Open, Create, or Append) and the file access (Read, Write, or ReadWrite). Additionally, the file share value determines the access other threads have to the file, including options like Delete, None, Read, ReadWrite, Write, or Inheritable.

string path = @"C:\sample.txt";
// Open the file for reading
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
{
    // Perform file operations here
    byte[] buffers = new byte[1024];
    int c;
    while ((c = fs.Read(buffers, 0, buf.Length)) > 0)
    {
        Console.WriteLine(Encoding.UTF8.GetString(buffers, 0, c));
    }
}

We create a byte buffer and an auxiliary variable.

The Read method reads a block of bytes from the stream and stores them in the provided buffer, while Encoding.UTF8.GetString decodes the byte sequence into a string.

C# File.OpenRead

The File.OpenRead method opens an existing file for reading, returning a read-only FileStream for the specified path. It is a convenience method that simplifies usage compared to File.Open.

string path = @"C:\sample.txt";
// Open the file for reading
using (FileStream fs = File.OpenRead(path))
{
    // Perform file operations here
    byte[] buffers = new byte[1024];
    int c;
    while ((c = fs.Read(buffers, 0, buf.Length)) > 0)
    {
        Console.WriteLine(Encoding.UTF8.GetString(buffers, 0, c));
    }
}

C# File.OpenText

The File.OpenText method opens an existing UTF-8 encoded text file for reading and returns a StreamReader for the specified path.

string path = @"C:\sample.txt";
// Open the file for reading
using (StreamReader sr = File.OpenText(path))
{
    // Perform file operations here
    string s = String.Empty;
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}

We read the text file line by line without needing to decode the bytes into a string manually.

C# File.OpenWrite

The File.OpenWrite method opens an existing file or creates a new file for writing, returning a FileStream object with write access to the specified path.

var path = "c:\sample.txt";  // Define the file path
// Open the file for writing (creates the file if it doesn't exist)
using FileStream fs = File.OpenWrite(path); 
// Create a StreamWriter to write text to the file
using StreamWriter sr = new StreamWriter(fs);
// Write lines to the file
sr.WriteLine("C# Programming\nASP.NET Core\nEntity Framework\nC# Example\n");

We open a FileStream to the specified path, then pass the stream to a StreamWriter, which writes characters using a specific encoding (UTF-8 by default).

C# File.ReadLines

The File.ReadLines method opens a text file, reads all its lines into an enumerable collection of strings, and then automatically closes the file.

var path = "c:\sample.txt";
var lines = File.ReadLines(path);
foreach (var line in lines)
{
    Console.WriteLine(line);
}

The example reads all lines of a text file, and the returned array of strings is iterated over using a foreach loop.

C# File.ReadAllBytes

The File.ReadAllBytes method opens a binary file, reads its contents into a byte array, and then closes the file.

var path = "c:\image.jpg";
byte[] data = File.ReadAllBytes(path);
int i = 0;
foreach (var c in data)
{
    Console.Write("{0:X2} ", c);
    i++;
    if (i % 10 == 0)   
        Console.WriteLine();
}

The example reads a image.jpg binary file, and the data is printed to the console in hexadecimal format.

C# File.WriteAllBytes

The File.WriteAllBytes method creates a new file, writes the specified byte array to the file, and then closes the file.

var path = "c:\sample.txt";
var text = "c#\nc\nc++\njava";
byte[] data = Encoding.UTF8.GetBytes(text);
File.WriteAllBytes(path, data);

We convert the text data into a byte array using Encoding.UTF8.GetBytes, and then write the array to the file with File.WriteAllBytes.

C# File.ReadAllText

The File.ReadAllText method opens a text file, reads all its contents into a string, and then closes the file. Note that this method is not recommended for very large files.

var path = "c:\sample.txt";
string readText = File.ReadAllText(path);
Console.WriteLine(readText);

C# File.WriteAllText

The File.WriteAllText method creates a new file, writes the specified contents to it, and then closes the file. If the target file already exists, it is overwritten.

var path = "c:\sample.txt";

string data = "c#\njavascript\nc++\nasp.net";
File.WriteAllText(path, data);

C# File.WriteAllLines

The File.WriteAllLines method creates a new file, writes one or more strings to the file, and then closes the file.

var path = "c:\sample.txt";
string[] data = { "c#", "c++", "java", "sql" };
File.WriteAllLines(path, data, Encoding.UTF8);

In the example, we have an array of strings, and we write these strings to a file in one operation using File.WriteAllLines.

C# File.AppendText

The File.AppendText method creates a StreamWriter that appends UTF-8 encoded text to an existing file, or creates a new file if the specified file does not exist.

var path = "c:\sample.txt";
using StreamWriter sw = File.AppendText(path);
sw.WriteLine("c#");
sw.WriteLine("c++");

C# File.AppendAllText

The File.AppendAllText method appends the specified string to a file, creating the file if it does not already exist.

var path = "c:\sample.txt";
var contents = "c#\nc++\njava\n";
File.AppendAllText(path, contents);

C# File.AppendAllLines

The File.AppendAllLines method appends lines to a file and then closes the file.

var path = "c:\sample.txt";
List<string> data = ["c#", "c", "c++"];
File.AppendAllLines(path, data);