728x90
The System.IO
namespace in C# provides types that allow synchronous and asynchronous reading and writing on data streams and files. It includes classes for managing directories, files, and streams, among other things.
Key Classes and Their Purposes:
- File:
- Provides static methods for file operations such as creation, deletion, copying, and moving.
- Example:
File.Create()
,File.Delete()
,File.ReadAllText()
.
- Directory:
- Provides static methods for directory operations such as creation, deletion, moving, and enumerating files and directories.
- Example:
Directory.CreateDirectory()
,Directory.Delete()
,Directory.GetFiles()
.
- FileInfo:
- Provides instance methods for creating, copying, deleting, moving, and opening files, and aids in the creation of
FileStream
objects. - Example:
FileInfo.Create()
,FileInfo.Delete()
,FileInfo.CopyTo()
.
- Provides instance methods for creating, copying, deleting, moving, and opening files, and aids in the creation of
- DirectoryInfo:
- Provides instance methods for creating, moving, and enumerating through directories and subdirectories.
- Example:
DirectoryInfo.Create()
,DirectoryInfo.Delete()
,DirectoryInfo.GetFiles()
.
- FileStream:
- Provides a stream for file operations, enabling reading and writing on files.
- Example:
FileStream.Read()
,FileStream.Write()
,FileStream.Seek()
.
- StreamReader:
- Implements a
TextReader
that reads characters from a byte stream in a particular encoding. - Example:
StreamReader.ReadLine()
,StreamReader.ReadToEnd()
.
- Implements a
- StreamWriter:
- Implements a
TextWriter
that writes characters to a stream in a particular encoding. - Example:
StreamWriter.WriteLine()
,StreamWriter.Write()
.
- Implements a
- Path:
- Provides methods for processing directory strings in a cross-platform manner.
- Example:
Path.Combine()
,Path.GetExtension()
,Path.GetFileName()
.
Example: Reading and Writing to a File
Here's a practical example that demonstrates reading from and writing to a file using StreamWriter
and StreamReader
:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Write to the file
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, System.IO!");
writer.WriteLine("This is a test file.");
}
// Read from the file
using (StreamReader reader = new StreamReader(filePath))
{
string content;
while ((content = reader.ReadLine()) != null)
{
Console.WriteLine(content);
}
}
// Delete the file
File.Delete(filePath);
}
}
Explanation:
- StreamWriter: Writes text to the file
example.txt
. - StreamReader: Reads the content from the file line by line.
- File.Delete: Deletes the file after reading its content.
728x90
반응형
'Software > C#' 카테고리의 다른 글
C# 시작하기 - DirectoryInfo (0) | 2025.01.11 |
---|---|
C# 시작하기 - FileInfo (0) | 2025.01.11 |
C# 시작하기 - System.IO.Directory (0) | 2025.01.11 |
C# 시작하기 - System.IO.File (0) | 2025.01.11 |
C# 시작하기 - 세션 (0) | 2024.08.19 |