-
Notifications
You must be signed in to change notification settings - Fork 5
File Handling
Sann Lynn Htun edited this page Nov 19, 2024
·
1 revision
File handling in C# is essential for performing various operations like reading from, writing to, and manipulating files. The System.IO namespace contains the necessary classes for file operations.
- Reading and Writing Files
Use
StreamReader
andStreamWriter
for text files andFileStream
for binary files.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamReader reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello, World!");
}
}
}
- FileStream
Use
FileStream
for more control over file operations, especially for binary data.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.bin";
using (FileStream fs = new FileStream(path, FileMode.Create))
{
byte[] data = { 0, 1, 2, 3, 4, 5 };
fs.Write(data, 0, data.Length);
}
}
}
- File Class
The
File
class provides static methods for common file operations, such as copying, deleting, and checking the existence of files.
using System;
using System.IO;
class Program
{
static void Main()
{
string sourcePath = "source.txt";
string destinationPath = "destination.txt";
// Copy file
File.Copy(sourcePath, destinationPath, true);
// Check if file exists
if (File.Exists(destinationPath))
{
Console.WriteLine("File copied successfully.");
}
// Delete file
File.Delete(destinationPath);
}
}
- StreamReader and StreamWriter: For reading and writing text files.
- FileStream: For binary file operations.
- File Class: For common file operations like copy, delete, and check existence.
-
Introduction to C#
What is C#? -
Variables and Data Types
Understand how to declare and use variables. -
Operators
Arithmetic, relational, and logical operators in C#. -
Control Statements
If-else, switch, and looping constructs.
-
Classes and Objects
Basics of OOP in C#. -
Inheritance
How to use inheritance effectively. -
Polymorphism
Method overriding and overloading. -
Encapsulation
Understanding access modifiers.
-
LINQ Basics
Working with Language Integrated Query. -
Asynchronous Programming
Introduction to async/await. -
File Handling
Reading and writing files.
-
Number Formatting
Formatting numbers in C#. -
Exception Handling
Handling runtime errors effectively. -
Working with Dates
DateTime and time zone handling. -
Using Keyword in C#
Different usages of theusing
keyword in C#.
-
Setting Up Development Environment
Installing Visual Studio and .NET SDK. - Useful Libraries Libraries and tools for C# development.