728x90
System.IO.File
is a class in the .NET framework that provides static methods for the creation, copying, deletion, moving, and opening of files. It also helps in reading and writing to files. Let's take a look at some commonly used methods of the File
class:
Common Methods:
Create:
// Creates or overwrites a file in the specified path using (FileStream fs = File.Create("path/to/file.txt")) { // You can write to the file here }
Copy:
// Copies a file to a new location File.Copy("path/to/source.txt", "path/to/destination.txt");
Delete:
// Deletes the specified file File.Delete("path/to/file.txt");
Move:
// Moves a file to a new location File.Move("path/to/source.txt", "path/to/destination.txt");
ReadAllText:
// Reads all text from a file string content = File.ReadAllText("path/to/file.txt"); Console.WriteLine(content);
WriteAllText:
// Writes text to a file, overwriting the file if it exists File.WriteAllText("path/to/file.txt", "Hello, World!");
Exists:
// Checks if the specified file exists if (File.Exists("path/to/file.txt")) { Console.WriteLine("File exists."); } else { Console.WriteLine("File does not exist."); }
Example Usage:
Here’s a quick example demonstrating the creation, writing, reading, and deletion of a file:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Create a file and write text to it
File.WriteAllText(filePath, "Hello, C# File Handling!");
// Read the text from the file
string content = File.ReadAllText(filePath);
Console.WriteLine("File Content: " + content);
// Check if the file exists
if (File.Exists(filePath))
{
Console.WriteLine("The file exists.");
}
// Delete the file
File.Delete(filePath);
Console.WriteLine("File deleted.");
}
}
This example demonstrates how to create a file, write text to it, read the text, check for its existence, and delete it.
728x90
반응형
'Software > C#' 카테고리의 다른 글
C# 시작하기 - System.IO (0) | 2025.01.11 |
---|---|
C# 시작하기 - System.IO.Directory (0) | 2025.01.11 |
C# 시작하기 - 세션 (0) | 2024.08.19 |
C# 시작하기 - HTTP 쿠키 (0) | 2024.08.17 |
C# 시작하기 - 멀티스레드 (0) | 2024.08.17 |