File Class
System.IO
Provides static methods and properties for the creation, copying, deletion, moving, and opening of files, and aids in the creation of Stream 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. -
AppendAllText
(string path, string contents)
Appends a string to the end of this file. If the file does not exist, this method creates a file, writes the specified string to the file, and then closes the file. If the file exists, its contents are appended.
-
Copy
(string sourceFileName, string destFileName)
Copies an existing file to a new location and allows the overwriting of an existing file.
-
Create
(string path)
Creates or overwrites a file in the specified path and returns a new FileStream.
-
Delete
(string path)
Deletes the specified file.
-
Exists
(string path)
Determines whether the specified file exists.
-
Move
(string sourceFileName, string destFileName)
Moves a specified file to a new location, with the option to specify a new file name.
-
ReadAllBytes
(string path)
Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
-
ReadAllLines
(string path)
Opens a text file, reads all lines of the file, and then closes the file.
-
ReadAllText
(string path)
Opens a text file, reads all lines of the file, and then closes the file.
-
WriteAllBytes
(string path, byte[] bytes)
Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
-
WriteAllLines
(string path, IEnumerable
contents) Creates a new file, writes a collection of strings to the file, and then closes the file. -
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.
AppendAllLines
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 to. The file will be created if it does not exist.
contents- The content to append to the file.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath or contents is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
string filePath = "myFile.txt";
List linesToAppend = new List { "Line 1", "Line 2", "Line 3" };
try
{
File.AppendAllLines(filePath, linesToAppend);
Console.WriteLine($"Successfully appended lines to {filePath}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
AppendAllText
Appends a string to the end of this file. If the file does not exist, this method creates a file, writes the specified string to the file, and then closes the file. If the file exists, its contents are appended.
Parameters
path- The file to append to. The file will be created if it does not exist.
contents- The string to append to the file.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath or contents is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "myLog.txt";
string logEntry = $"[{DateTime.Now}] New log entry.\n";
try
{
File.AppendAllText(filePath, logEntry);
Console.WriteLine($"Successfully appended to {filePath}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Copy
Copies an existing file to a new location and allows the overwriting of an existing file.
Parameters
sourceFileName- The path and name of the file to copy.
destFileName- The path and name to which the copied file will be copied. This parameter can also be a file name.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionsourceFileName or destFileName is null.DirectoryNotFoundExceptionThe path specified is invalid (for example, it is on an unmapped drive).FileNotFoundExceptionThe source file was not found.IOExceptionAn I/O error has occurred.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string sourceFile = "original.txt";
string destinationFile = "backup.txt";
// Create a dummy source file for the example
File.WriteAllText(sourceFile, "This is the original content.");
try
{
File.Copy(sourceFile, destinationFile, true); // true to overwrite if exists
Console.WriteLine($"Copied '{sourceFile}' to '{destinationFile}'");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Create
Creates or overwrites a file in the specified path and returns a new FileStream.
Parameters
path- The name and path of the file to create.
Returns
FileStream- A new FileStream object for the specified file.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).IOExceptionThe file is already in use.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "newFile.txt";
try
{
using (FileStream fs = File.Create(filePath))
{
// You can write to the stream here if needed
Byte[] info = new Byte[4] { 82, 111, 115, 115 };
fs.Write(info, 0, info.Length);
}
Console.WriteLine($"File '{filePath}' created successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Delete
Deletes the specified file.
Parameters
path- The name of the file to be deleted. Wildcard characters are not supported.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).IOExceptionThe file is in use and cannot be deleted.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "fileToDelete.txt";
// Create a dummy file to delete
File.WriteAllText(filePath, "This file will be deleted.");
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
Console.WriteLine($"File '{filePath}' deleted successfully.");
}
else
{
Console.WriteLine($"File '{filePath}' does not exist.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Exists
Determines whether the specified file exists.
Parameters
path- The file to check.
Returns
booltrueif the caller has the required permissions andpathcontains the name of an existing file; otherwise,false. This method also returnsfalseif path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, an exception is thrown andfalseis not returned.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string existingFilePath = "existing.txt";
string nonExistingFilePath = "nonexistent.txt";
// Create a dummy file for testing
File.WriteAllText(existingFilePath, "This file exists.");
try
{
if (File.Exists(existingFilePath))
{
Console.WriteLine($"File '{existingFilePath}' exists.");
}
else
{
Console.WriteLine($"File '{existingFilePath}' does not exist.");
}
if (File.Exists(nonExistingFilePath))
{
Console.WriteLine($"File '{nonExistingFilePath}' exists.");
}
else
{
Console.WriteLine($"File '{nonExistingFilePath}' does not exist.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the dummy file
if (File.Exists(existingFilePath))
{
File.Delete(existingFilePath);
}
}
}
}
Move
Moves a specified file to a new location, with the option to specify a new file name.
Parameters
sourceFileName- The name and path for the current file, being moved.
destFileName- The name and path to move the current file to.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionsourceFileName or destFileName is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).FileNotFoundExceptionThe source file was not found.IOExceptionThe destination file exists, or the source file is in use.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string originalFilePath = "toBeMoved.txt";
string newFilePath = "movedFile.txt";
// Create a dummy file for the example
File.WriteAllText(originalFilePath, "Content for the file to be moved.");
try
{
if (File.Exists(originalFilePath))
{
File.Move(originalFilePath, newFilePath);
Console.WriteLine($"File moved from '{originalFilePath}' to '{newFilePath}'");
}
else
{
Console.WriteLine($"Source file '{originalFilePath}' not found.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the moved file if it exists
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
}
}
}
}
ReadAllBytes
Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
Parameters
path- The file to open for reading.
Returns
byte[]- A byte array containing the contents of the file.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).FileNotFoundExceptionThe file specified in path was not found.IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "binaryData.bin";
// Create a dummy binary file for the example
byte[] dataToWrite = { 0x01, 0x02, 0x03, 0x04, 0x05 };
File.WriteAllBytes(filePath, dataToWrite);
try
{
byte[] fileBytes = File.ReadAllBytes(filePath);
Console.WriteLine($"Read {fileBytes.Length} bytes from '{filePath}'.");
// Process the byte array as needed
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the dummy file
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}
ReadAllLines
Opens a text file, reads all lines of the file, and then closes the file.
Parameters
path- The file to read.
Returns
string[]- A string array where each element is a line of the file.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).FileNotFoundExceptionThe file specified in path was not found.IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "lines.txt";
// Create a dummy file with multiple lines
string[] linesToWrite = { "First line", "Second line", "Third line" };
File.WriteAllLines(filePath, linesToWrite);
try
{
string[] fileLines = File.ReadAllLines(filePath);
Console.WriteLine($"Read {fileLines.Length} lines from '{filePath}':");
foreach (string line in fileLines)
{
Console.WriteLine($"- {line}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the dummy file
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}
ReadAllText
Opens a text file, reads all lines of the file, and then closes the file.
Parameters
path- The file to read.
Returns
string- A string containing all the content of the file.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).FileNotFoundExceptionThe file specified in path was not found.IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "content.txt";
// Create a dummy file with content
string fileContent = "This is the content of the file.\nIt has multiple lines.";
File.WriteAllText(filePath, fileContent);
try
{
string content = File.ReadAllText(filePath);
Console.WriteLine($"Content of '{filePath}':");
Console.WriteLine(content);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the dummy file
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}
WriteAllBytes
Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Parameters
path- The file to write to.
bytes- The byte array to write to the file.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath or bytes is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "output.bin";
byte[] dataToWrite = { 0xAA, 0xBB, 0xCC, 0xDD };
try
{
File.WriteAllBytes(filePath, dataToWrite);
Console.WriteLine($"Successfully wrote {dataToWrite.Length} bytes to '{filePath}'.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the created file
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}
WriteAllLines
Creates a new file, writes a collection of strings to the file, and then closes the file.
Parameters
path- The file to write to.
contents- The string array to write to the file.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath or contents is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
string filePath = "outputLines.txt";
List linesToWrite = new List { "First line written.", "Second line written.", "Third line written." };
try
{
File.WriteAllLines(filePath, linesToWrite);
Console.WriteLine($"Successfully wrote {linesToWrite.Count} lines to '{filePath}'.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the created file
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}
WriteAllText
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.
Returns
void- This method does not return a value.
Exceptions
ArgumentExceptionThe path is a zero-length string, contains only white space, or contains one or more invalid characters.ArgumentNullExceptionpath or contents is null.DirectoryNotFoundExceptionThe specified path is invalid (for example, it is on an unmapped drive).IOExceptionAn I/O error occurred while opening the file.PathTooLongExceptionThe specified path, file name, or both exceed the system-defined maximum length.UnauthorizedAccessExceptionThe caller does not have the required permission.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = "outputText.txt";
string contentToWrite = "This is the text content that will be written to the file.";
try
{
File.WriteAllText(filePath, contentToWrite);
Console.WriteLine($"Successfully wrote text to '{filePath}'.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the created file
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}