Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧠 Introduction
This chapter combines three core aspects of real-world C#
development:
These skills allow developers to build practical,
data-driven applications that persist and retrieve data, such as finance tools,
inventory systems, or CRUD-based software.
📁 Part 1: File Handling
in C#
🔹 Namespaces Required
using
System;
using
System.IO;
✅ Creating and Writing to a File
string
filePath = "data.txt";
File.WriteAllText(filePath,
"Hello, File Handling!");
Console.WriteLine("File
created and data written.");
✅ Reading from a File
string
content = File.ReadAllText("data.txt");
Console.WriteLine("Content:
" + content);
✅ Appending Data
File.AppendAllText("data.txt",
"\nNew line added.");
✅ Checking File Existence
if
(File.Exists("data.txt"))
Console.WriteLine("File found.");
else
Console.WriteLine("File not
found.");
✅ Deleting a File
File.Delete("data.txt");
📋 File Handling Methods
Comparison
Method |
Purpose |
File.WriteAllText |
Write data to file |
File.ReadAllText |
Read all text |
File.AppendAllText |
Add data without
overwriting |
File.Exists |
Check if a
file exists |
File.Delete |
Remove a file |
✅ Using StreamReader and
StreamWriter
using
(StreamWriter writer = new StreamWriter("sample.txt"))
{
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
}
csharp
CopyEdit
using
(StreamReader reader = new StreamReader("sample.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
}
💾 Part 2: Database
Connectivity with ADO.NET
🔹 ADO.NET Overview
ADO.NET is the standard .NET API for accessing relational
databases such as SQL Server, MySQL, or SQLite.
🔹 Required Namespace
using
System.Data.SqlClient;
✅ Basic SQL Server Connection
string
connectionString =
"Server=localhost;Database=TestDB;Trusted_Connection=True;";
using
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
Console.WriteLine("Connected
to database!");
✅ Creating a Table
string
sql = "CREATE TABLE Employees (Id INT, Name NVARCHAR(50))";
SqlCommand
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
✅ Inserting Data
string
insertSql = "INSERT INTO Employees VALUES (1, 'Alice')";
SqlCommand
insertCmd = new SqlCommand(insertSql, conn);
insertCmd.ExecuteNonQuery();
✅ Reading Data
string
readSql = "SELECT * FROM Employees";
SqlCommand
readCmd = new SqlCommand(readSql, conn);
SqlDataReader
reader = readCmd.ExecuteReader();
while
(reader.Read())
{
Console.WriteLine($"ID: {reader[0]},
Name: {reader[1]}");
}
📋 ADO.NET Command Summary
Method |
Purpose |
SqlConnection |
Establish DB
connection |
SqlCommand |
Executes SQL
commands |
ExecuteReader() |
Fetches data |
ExecuteNonQuery() |
Executes
insert/update/delete |
SqlDataReader |
Reads result set
row-by-row |
🏗️ Part 3: Building a C#
Console Application
Let’s combine everything into a mini project — a
basic Employee Management System.
✅ Step 1: Define the Employee
Class
class
Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
✅ Step 2: Create a Database
Helper
class
Database
{
string connString =
"Server=localhost;Database=TestDB;Trusted_Connection=True;";
public void AddEmployee(Employee emp)
{
using SqlConnection conn = new
SqlConnection(connString);
conn.Open();
string sql = $"INSERT INTO
Employees VALUES ({emp.Id}, '{emp.Name}')";
SqlCommand cmd = new SqlCommand(sql,
conn);
cmd.ExecuteNonQuery();
}
public void ListEmployees()
{
using SqlConnection conn = new
SqlConnection(connString);
conn.Open();
SqlCommand cmd = new
SqlCommand("SELECT * FROM Employees", conn);
SqlDataReader reader =
cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"ID:
{reader["Id"]}, Name: {reader["Name"]}");
}
}
}
✅ Step 3: Program Logic
class
Program
{
static void Main()
{
Database db = new Database();
Console.Write("Enter ID: ");
int id =
Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Name:
");
string name = Console.ReadLine();
db.AddEmployee(new Employee { Id = id,
Name = name });
Console.WriteLine("Employee added
successfully.\n");
Console.WriteLine("Current
Employees:");
db.ListEmployees();
}
}
✅ Output Example
Enter ID: 1
Enter Name: Alice
Employee added successfully.
Current Employees:
ID: 1, Name: Alice
📚 Real-World Use Cases
Feature |
Used For |
File Handling |
Logging,
configuration, backup |
Database |
Storing
records, analytics, transactions |
Application |
CRUD apps, dashboards,
console utilities |
📋 Summary Table
Concept |
Description |
File.WriteAllText |
Write content to a
file |
StreamReader |
Read file
line-by-line |
SqlConnection |
Connects to SQL Server |
SqlCommand |
Executes SQL queries |
Console App |
User interaction + DB
+ logic |
A: Yes, especially with Visual Studio and .NET’s extensive documentation and community support.
A: Not at all. C# is independent and designed for new learners.
A: Yes, using ASP.NET Core you can build scalable web apps and APIs.
A: Both are similar syntactically, but C# is part of the Microsoft .NET ecosystem and often integrates better with Windows technologies.
A: Not anymore. With .NET Core and .NET 8, C# is cross-platform.
A: Absolutely. It is the main language used in Unity.
A: Visual Studio is the most powerful and popular IDE for C# development.
A: Yes, with Xamarin or .NET MAUI, C# can build cross-platform mobile apps.
A: C# continues to evolve with modern features and has strong backing from Microsoft, making it future-proof.
A: No, you can code, compile, and run C# locally, though some online libraries/tools may require internet.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)