File Class
Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Inheritance Hierarchy: Object > System.IO.File
Fields
`public static readonly string PathSeparator`
Indicates the directory separator character of the current file system.
`public static readonly string TempPath`
Gets the fully qualified path to the temporary directory on the current computer.
Methods
`public static FileStream Create(string path)`
public static FileStream Create(string path)
Creates or overwrites a file in the specified path.
Parameters
- path: The name of the file to create.
Returns
- A new file or an overwritten file. The stream is positioned at the beginning of the file.
Example
// Example for File.Create
using System;
using System.IO;
public class Example
{
public static void Main()
{
string path = @"C:\temp\MyFile.txt";
try
{
using (FileStream fs = File.Create(path))
{
// You can write to the file here if needed
// byte[] info = new System.Text.UTF8Encoding(true).GetBytes("This is my text file.");
// fs.Write(info, 0, info.Length);
Console.WriteLine($"File '{path}' created successfully.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
`public static void Copy(string sourceFileName, string destFileName)`
public static void Copy(string sourceFileName, string destFileName)
Copies an existing file to a new location.
Parameters
- sourceFileName: The path of the file to copy.
- destFileName: The name of the destination file.
Example
// Example for File.Copy
using System;
using System.IO;
public class Example
{
public static void Main()
{
string source = @"C:\temp\source.txt";
string destination = @"C:\temp\destination.txt";
// Create a dummy source file for demonstration
if (!File.Exists(source))
{
File.WriteAllText(source, "This is the source file content.");
}
try
{
File.Copy(source, destination, true); // true overwrites if destination exists
Console.WriteLine($"File '{source}' copied to '{destination}'.");
}
catch (IOException copyError)
{
Console.WriteLine($"IO Error: {copyError.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
`public static void Delete(string path)`
public static void Delete(string path)
Deletes the specified file.
Parameters
- path: The path of the file to be deleted.
Example
// Example for File.Delete
using System;
using System.IO;
public class Example
{
public static void Main()
{
string pathToDelete = @"C:\temp\fileToDelete.txt";
// Create a dummy file to delete
if (!File.Exists(pathToDelete))
{
File.WriteAllText(pathToDelete, "This file will be deleted.");
Console.WriteLine($"File '{pathToDelete}' created.");
}
try
{
File.Delete(pathToDelete);
Console.WriteLine($"File '{pathToDelete}' deleted successfully.");
}
catch (IOException deleteError)
{
Console.WriteLine($"IO Error: {deleteError.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
`public static bool Exists(string path)`
public static bool Exists(string path)
Determines whether the specified file exists.
Parameters
- path: The file to check.
Returns
trueif the caller has the required permissions andpathcontains a file; otherwise,false.
Example
// Example for File.Exists
using System;
using System.IO;
public class Example
{
public static void Main()
{
string filePath = @"C:\temp\checkFile.txt";
if (File.Exists(filePath))
{
Console.WriteLine($"File '{filePath}' exists.");
}
else
{
Console.WriteLine($"File '{filePath}' does not exist.");
}
// Create a file and check again
File.WriteAllText(filePath, "Checking existence.");
Console.WriteLine($"Created '{filePath}'.");
if (File.Exists(filePath))
{
Console.WriteLine($"File '{filePath}' now exists.");
File.Delete(filePath); // Clean up
}
}
}
`public static string ReadAllText(string path)`
public static string ReadAllText(string path)
Opens a text file, reads all lines of the file, and then closes the file.
Parameters
- path: The file to read.
Returns
- A string containing all lines of the file.
Example
// Example for File.ReadAllText
using System;
using System.IO;
public class Example
{
public static void Main()
{
string path = @"C:\temp\readExample.txt";
string content = "Hello, .NET File API!\nThis is the second line.";
// Create a file with content
File.WriteAllText(path, content);
Console.WriteLine($"File '{path}' created with content.");
try
{
string fileContent = File.ReadAllText(path);
Console.WriteLine($"\nContent of '{path}':");
Console.WriteLine(fileContent);
}
catch (FileNotFoundException)
{
Console.WriteLine($"Error: The file '{path}' was not found.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
if (File.Exists(path)) File.Delete(path); // Clean up
}
}
}
`public static void WriteAllText(string path, string contents)`
public static void 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.
Example
// Example for File.WriteAllText
using System;
using System.IO;
public class Example
{
public static void Main()
{
string path = @"C:\temp\writeExample.txt";
string textToWrite = "This is some text to write into the file.";
try
{
File.WriteAllText(path, textToWrite);
Console.WriteLine($"Successfully wrote text to '{path}'.");
// Optional: Read back to verify
string readText = File.ReadAllText(path);
Console.WriteLine($"\nContent read from '{path}':\n{readText}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
if (File.Exists(path)) File.Delete(path); // Clean up
}
}
}
Properties
`public static long MaxPath`
Gets the maximum length for a file path that is supported by the common language runtime.
Remarks
The File class is a static class and cannot be instantiated. It provides static methods that encapsulate file operations. It is important to handle exceptions that may occur during file operations, such as `FileNotFoundException`, `IOException`, `DirectoryNotFoundException`, and `UnauthorizedAccessException`.
For more advanced file stream operations, consider using the FileStream class directly, which provides more control over file access and buffering.