C# Programming Tutorial: From Fundamentals to Advanced Application Development

5.85K 0 0 0 0

📘 Chapter 6: File Handling, Databases, and Application Building in C#

🧠 Introduction

This chapter combines three core aspects of real-world C# development:

  • File Handling – Read/write data to local storage.
  • Database Connectivity – Interact with relational databases (SQL Server).
  • Application Building – Create a complete working C# console application.

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.");

  • WriteAllText() creates or overwrites the file.
  • Automatically closes the file when done.

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

Back

FAQs


1. Q: Is C# easy to learn for beginners?

A: Yes, especially with Visual Studio and .NET’s extensive documentation and community support.

2. Q: Do I need to know C or C++ before learning C#?

A: Not at all. C# is independent and designed for new learners.

3. Q: Can I build web apps using C#?

A: Yes, using ASP.NET Core you can build scalable web apps and APIs.

4. Q: What’s the difference between C# and Java?

A: Both are similar syntactically, but C# is part of the Microsoft .NET ecosystem and often integrates better with Windows technologies.

5. Q: Is C# only for Windows development?

A: Not anymore. With .NET Core and .NET 8, C# is cross-platform.

6. Q: Is C# good for game development?

A: Absolutely. It is the main language used in Unity.

7. Q: Which IDE is best for C#?

A: Visual Studio is the most powerful and popular IDE for C# development.

8. Q: Can I use C# for mobile development?

 A: Yes, with Xamarin or .NET MAUI, C# can build cross-platform mobile apps.

9. Q: What is the future of C# in 2025 and beyond?

A: C# continues to evolve with modern features and has strong backing from Microsoft, making it future-proof.

10. Q: Do I need internet to use C# tools?

A: No, you can code, compile, and run C# locally, though some online libraries/tools may require internet.