System.IO Namespace

Provides types that allow reading and writing to and from streams and files. These types also provide basic support for file and directory operations.

File

File Class

Represents a static class that provides methods for creating, copying, deleting, moving, and opening files. This class also helps in the creation of FileStream objects.

Methods

AppendAllLines(string path, IEnumerable contents)

Appends specified lines to a file, and then closes the file. If the file does not exist, it is created.

Parameters:
  • path: The file to append the specified lines to.
  • contents: The lines to append to the file.
using System.IO;

public class Example
{
public static void Main()
{
string filePath = "myFile.txt";
string[] lines = { "First line.", "Second line." };

File.AppendAllLines(filePath, lines);
Console.WriteLine("Lines appended to file.");
}
}

ReadAllText(string path)

Opens a text file, reads all lines of the file, and then closes the file.

Parameters:
  • path: The file to read.
using System.IO;

public class Example
{
public static void Main()
{
string filePath = "myFile.txt";
string content = File.ReadAllText(filePath);
Console.WriteLine("File content:\n{0}", content);
}
}

WriteAllText(string path, string contents)

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

Parameters:
  • path: The file to write to.
  • contents: The string to write to the file.
using System.IO;

public class Example
{
public static void Main()
{
string filePath = "newFile.txt";
string text = "This is the content written to the new file.";

File.WriteAllText(filePath, text);
Console.WriteLine("Content written to file.");
}
}

Exists(string path)

Determines whether the specified file exists.

Parameters:
  • path: The file to check.
using System.IO;

public class Example
{
public static void Main()
{
string filePath = "config.json";
if (File.Exists(filePath))
{
Console.WriteLine("Configuration file exists.");
}
else
{
Console.WriteLine("Configuration file not found.");
}
}
}

Directory

Directory Class

Represents a static class that provides methods for creating, moving, and enumerating through directories and subdirectories. This class also provides methods for reading and writing to files.

Methods

CreateDirectory(string path)

Creates all the directories and subdirectories in the specified path unless they already exist.

Parameters:
  • path: The directory to create.
using System.IO;

public class Example
{
public static void Main()
{
string dirPath = "MyNewApp/Data";
Directory.CreateDirectory(dirPath);
Console.WriteLine("Directory '{0}' created.", dirPath);
}
}

Delete(string path, bool recursive)

Deletes a specified directory and a specified reason. If the directory is not empty, this method will throw an exception unless recursive is true.

Parameters:
  • path: The directory to delete.
  • recursive: True to remove directories, subdirectories, and files in path; otherwise, false.
using System.IO;

public class Example
{
public static void Main()
{
string dirPath = "TemporaryFiles";
// Ensure directory exists first for demonstration
Directory.CreateDirectory(dirPath);
File.WriteAllText(Path.Combine(dirPath, "temp.txt"), "temp content");

if (Directory.Exists(dirPath))
{
Directory.Delete(dirPath, true);
Console.WriteLine("Directory '{0}' deleted recursively.", dirPath);
}
}
}

Exists(string path)

Determines whether the given path refers to an existing directory on disk.

Parameters:
  • path: The path to check.
using System.IO;

public class Example
{
public static void Main()
{
string dirPath = "AppData/Settings";
if (Directory.Exists(dirPath))
{
Console.WriteLine("Settings directory exists.");
}
else
{
Console.WriteLine("Settings directory does not exist.");
}
}
}

Path

Path Class

Provides properties and methods, for creating, manipulating, and obtaining information about paths.

Properties

PathSeparator Property

Gets the directory separator character for the current platform.

using System;
using System.IO;

public class Example
{
public static void Main()
{
Console.WriteLine("Path separator: {0}", Path.PathSeparator);
}
}

DirectorySeparatorChar Property

Gets the directory separator character for the current platform.

using System;
using System.IO;

public class Example
{
public static void Main()
{
Console.WriteLine("Directory separator: {0}", Path.DirectorySeparatorChar);
}
}

Methods

Combine(string path1, string path2)

Combines two strings into a path. The result is valid on both the current platform and UNC servers.

Parameters:
  • path1: The first path.
  • path2: The second path.
using System.IO;

public class Example
{
public static void Main()
{
string folder = "Documents";
string file = "report.docx";
string fullPath = Path.Combine(folder, file);
Console.WriteLine("Combined path: {0}", fullPath);
}
}

GetFileName(string path)

Returns the file name of the specified path string.

Parameters:
  • path: The path string to return the file name from.
using System.IO;

public class Example
{
public static void Main()
{
string filePath = "/Users/Me/Documents/report.docx";
string fileName = Path.GetFileName(filePath);
Console.WriteLine("File name: {0}", fileName);
}
}

Stream

Stream Class

Abstract base class for all streams. Provides the fundamental methods for working with streams, such as reading, writing, and seeking.

Properties

CanRead Property

Gets a value indicating whether the stream supports reading.

CanWrite Property

Gets a value indicating whether the stream supports writing.

CanSeek Property

Gets a value indicating whether the stream supports seeking.

Length Property

Gets the length in bytes of the stream.

Position Property

Gets or sets the current position within the stream.

Methods

Read(byte[] buffer, int offset, int count)

Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

Parameters:
  • buffer: An array of bytes. When this method returns, the buffer contains the specified sequence of bytes.
  • offset: The zero-based index in buffer at which to begin copying bytes.
  • count: The maximum number of bytes to read.

Write(byte[] buffer, int offset, int count)

Writes a sequence of bytes to the current stream and advances the position within the stream by the number of bytes written.

Parameters:
  • buffer: An array of bytes. This method copies count bytes from buffer to the current stream.
  • offset: The zero-based index in buffer from which to begin copying bytes.
  • count: The number of bytes to write.

Seek(long offset, SeekOrigin origin)

Sets the position within the current stream to the specified value.

Parameters:
  • offset: A byte offset relative to the origin parameter.
  • origin: A value of type SeekOrigin indicating the reference point to use for offset.

Flush()

Clears all buffers for this stream and causes any buffered data to be written to the underlying device.

FileInfo

FileInfo Class

Provides instance methods for the creation, deletion, moving, and opening of files, and aids in their creation, deletion, moving, and opening.

Constructors

FileInfo(string fileName)

Initializes a new instance of the FileInfo class for the specified file path.

Parameters:
  • fileName: The name of the file.

Properties

Name Property

Gets the name of the file.

FullName Property

Gets the fully qualified path of the file or directory.

Exists Property

Gets a value indicating whether the specified file exists.

Length Property

Gets the size of the current file in bytes.

Methods

Open(FileMode mode)

Opens a FileStream object on the current file using the specified mode.

Parameters:
  • mode: A FileMode value that specifies whether to create, open, append, or overwrite the file.

Delete()

Deletes this file.

MoveTo(string destFileName)

Moves a specified file to a new location, with the option to specify a new file name.

Parameters:
  • destFileName: The name of the destination file.

DirectoryInfo

DirectoryInfo Class

Provides instance methods for the creation, deletion, moving, and enumeration of directories, and aids in their creation, deletion, moving, and opening.

Constructors

DirectoryInfo(string path)

Initializes a new instance of the DirectoryInfo class for the specified path.

Parameters:
  • path: The path of the directory.

Properties

Name Property

Gets the name of the directory.

FullName Property

Gets the fully qualified path of the directory.

Exists Property

Gets a value indicating whether the specified directory exists.

Methods

Create()

Creates this directory.

Delete(bool recursive)

Deletes this directory, optionally with a parameter that indicates whether to remove directories, subdirectories, and files in this instance in error.

Parameters:
  • recursive: True to remove directories, subdirectories, and files in path; otherwise, false.

GetFiles()

Gets a FileInfo array representing all the files in the current directory.

GetDirectories()

Gets a DirectoryInfo array representing the subdirectories in the current directory.

StreamReader

StreamReader Class

Implements a TextReader that reads characters from a byte stream in a particular encoding.

Constructors

StreamReader(string path)

Initializes a new instance of the StreamReader class for the specified file path.

Parameters:
  • path: The complete file path to read.

StreamReader(Stream stream)

Initializes a new instance of the StreamReader class for the specified stream.

Parameters:
  • stream: The stream to read from.

Methods

ReadLine()

Reads the next line of characters from the current stream and returns data as a string.

ReadToEnd()

Reads to the end of the stream and returns all characters that have been read.

StreamWriter

StreamWriter Class

Implements a TextWriter for writing characters to a stream in a particular encoding.

Constructors

StreamWriter(string path)

Initializes a new instance of the StreamWriter class for the specified file path.

Parameters:
  • path: The complete file path to write to.

StreamWriter(Stream stream)

Initializes a new instance of the StreamWriter class for the specified stream.

Parameters:
  • stream: The stream to write to.

Methods

WriteLine(string value)

Writes a string to the stream and followed by a line terminator.

Parameters:
  • value: The string to write.

Write(string value)

Writes a string to the stream.

Parameters:
  • value: The string to write.

Flush()

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

BinaryReader

BinaryReader Class

Reads primitive data types from a stream in binary format.

Constructors

BinaryReader(Stream input)

Initializes a new instance of the BinaryReader class using the specified stream and a UTF-8 encoding.

Parameters:
  • input: The stream to read from.

Methods

ReadInt32()

Reads a 32-bit signed integer from the current stream and advances the stream position by four bytes.

ReadString()

Reads the next string from the current stream. The string is prefixed with the length, as a 32-bit integer, to read.

BinaryWriter

BinaryWriter Class

Writes primitive data types to a stream in binary format.

Constructors

BinaryWriter(Stream output)

Initializes a new instance of the BinaryWriter class using the specified stream and a UTF-8 encoding.

Parameters:
  • output: The stream to write to.

Methods

Write(int value)

Writes a 32-bit signed integer to the current stream and advances the stream position by four bytes.

Parameters:
  • value: The 32-bit signed integer to write.

Write(string value)

Writes a string to the current stream.

Parameters:
  • value: The string to write.

Flush()

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

MemoryStream

MemoryStream Class

Creates a stream whose backing store is memory. This class cannot be inherited.

Constructors

MemoryStream()

Initializes a new instance of the MemoryStream class with an expandable capacity or a specific capacity.

MemoryStream(byte[] buffer)

Initializes a new instance of the MemoryStream class based on the specified byte array.

Parameters:
  • buffer: The array of bytes from which to create the stream.

Methods

ToArray()

Creates a byte array, to the size of the stream.

FileStream

FileStream Class

Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations. This class cannot be inherited.

Constructors

FileStream(string path, FileMode mode)

Initializes a new instance of the FileStream class with the specified path and mode.

Parameters:
  • path: The file to be opened.
  • mode: A FileMode value that specifies whether to create, open, append, or overwrite the file.

Properties

CanSeek Property

Gets a value indicating whether the current stream supports seeking.

Methods

Close()

Closes the current FileStream and releases any resources such as file handles.