Ad Code

✨🎆 Diwali Dhamaka Offer! 🎆✨

Get 20% OFF on All Courses at Shiva Concept Solution click

File Handling Concept in C#

File handling concept in C#:-

Introduction

File handling in C# is a crucial aspect of many applications, providing the capability to create, read, write, and append files. This guide will explore the fundamental file handling operations in C#, offering practical examples for each operation to ensure you grasp the concepts effectively.

1. Creating a File in C#

Creating a file in C# involves using the File class from the System.IO namespace. This operation checks if the file exists and, if not, creates a new file.

Example: Creating a File

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        // Check if file already exists. If yes, delete it. 
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        // Create a new file     
        using (FileStream fs = File.Create(path))
        {
            Console.WriteLine("File created successfully.");
        }
    }
}

2. Writing to a File in C#

Writing to a file can be achieved using the StreamWriter class. This allows you to write text data to a file efficiently.

Example: Writing to a File

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        // Create a new file and write some text to it
        using (StreamWriter sw = new StreamWriter(path))
        {
            sw.WriteLine("Hello, World!");
            sw.WriteLine("Welcome to file handling in C#.");
            Console.WriteLine("Text written to file successfully.");
        }
    }
}

3. Reading from a File in C#

Reading from a file involves using the StreamReader class, which reads text data from a file and allows you to process it line by line or as a whole.

Example: Reading from a File

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        // Check if file exists before attempting to read
        if (File.Exists(path))
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string content = sr.ReadToEnd();
                Console.WriteLine("File Content:");
                Console.WriteLine(content);
            }
        }
        else
        {
            Console.WriteLine("File does not exist.");
        }
    }
}

4. Appending to a File in C#

Appending to a file is done using the StreamWriter class with the append parameter set to true. This ensures that new data is added to the end of the file without overwriting existing content.

Example: Appending to a File

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        // Append text to an existing file
        using (StreamWriter sw = new StreamWriter(path, true))
        {
            sw.WriteLine("Appending new text to the file.");
            Console.WriteLine("Text appended to file successfully.");
        }
    }
}



Operation on File:-


1)  Write File:-

It is used to save the record on file

using System.IO;

class FileHandlingOperation
    {
        public static void Main()
        {
            File.WriteAllText("D://mydemo.txt", "Welcome in File Handling");
            Console.ReadKey();
        }
    }

2)  Read File

class FileHandlingOperation
    {
        public static void Main()
        {
           String s= File.ReadAllText("D://mydemo.txt");
           Console.WriteLine(s);
            Console.ReadKey();
        }
    }

3)  Append File Operation:-


    class FileHandlingOperation
    {
        public static void Main()
        {
            File.AppendAllText("D://mydemo.txt", "Welcome in File Handling");
            Console.ReadKey();
        }
    }


Another Example of File Handling Operation:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Project2
{
    class FileHandlingOperation
    {
        string data = "";
        void CreateFile()
        {
           FileStream fs= File.Create("D://mydata1.txt");
           fs.Close();
            
        }
        void WriteFile()
        {

          //  Console.WriteLine("Enter data");
          //  data = Console.ReadLine();
            File.WriteAllText("D://si.txt",data);
            float p = 50000, r=2, t=3, si;
             si = (p * r * t) / 100;
            File.WriteAllText("D://si.txt", "Result is "+si);

        }

        void ReadFile()
        {
            String s = File.ReadAllText("D://mydata.txt");
            Console.WriteLine(s);
        }

        void AppendFile()
        {
            Console.WriteLine("Enter data");
            data = Console.ReadLine();
            File.AppendAllText("D://mydata.txt",data);

        }

        static void Main()
        {
            FileHandlingOperation obj = new FileHandlingOperation();
         //   obj.CreateFile();
              obj.WriteFile();
          //   obj.AppendFile();
            obj.ReadFile();
            Console.ReadKey();
        }

    }
}

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,............................................................


Conclusion

File handling in C# is a fundamental aspect of software development that allows you to perform various operations on files, such as creating, reading, writing, and appending. By understanding and utilizing the FileFileStreamStreamWriter, and StreamReader classes, you can effectively manage file operations in your applications.

Here’s a summary of the key operations covered:

  1. Creating a File: Using File.Create.

  2. Writing to a File: Using StreamWriter.

  3. Reading from a File: Using StreamReader.

  4. Appending to a File: Using StreamWriter with append parameter.


How to read | write and append data in Binary File:

A binary file stores data in binary (0s and 1s) format instead of plain text.
We use classes like FileStream and BinaryWriter / BinaryReader to handle them.

✅ Example: Writing and Reading a Binary File in C#
using System;
using System.IO;

namespace BinaryFileExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = "d:\\studentdata.bin";

            // ---------- Writing Data to Binary File ----------
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            using (BinaryWriter writer = new BinaryWriter(fs))
            {
                int rollNo = 101;
                string name = "Rahul Sharma";
                double marks = 89.75;

                writer.Write(rollNo);
                writer.Write(name);
                writer.Write(marks);

                Console.WriteLine("Data written successfully to binary file.");
            }

            // ---------- Reading Data from Binary File ----------
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (BinaryReader reader = new BinaryReader(fs))
            {
                int rollNo = reader.ReadInt32();
                string name = reader.ReadString();
                double marks = reader.ReadDouble();

                Console.WriteLine("\n--- Data Read from Binary File ---");
                Console.WriteLine("Roll No : " + rollNo);
                Console.WriteLine("Name    : " + name);
                Console.WriteLine("Marks   : " + marks);
            }

            Console.ReadLine();
        }
    }
}

🧾 Output
Data written successfully to binary file.

--- Data Read from Binary File ---
Roll No : 101
Name    : Rahul Sharma
Marks   : 89.75

📂 File Info

File created: d:\studentdata.bin

It contains binary data (not human-readable in Notepad).

You can open it with a hex editor to see raw bytes.

🧠 How to Read and Write data into CSV File

A CSV (Comma-Separated Values) file stores data in plain text — each line represents a record, and columns are separated by commas.

Example:

RollNo,Name,Marks
101,Rahul,89.5
102,Priya,92.0
103,Amit,78.25

✅ Example 1: Write Data to CSV File
using System;
using System.IO;

namespace CSVExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string path = "d:\\students.csv";

            // Create and write data into CSV
            using (StreamWriter writer = new StreamWriter(path))
            {
                // Write header
                writer.WriteLine("RollNo,Name,Marks");

                // Write student data
                writer.WriteLine("101,Rahul,89.5");
                writer.WriteLine("102,Priya,92.0");
                writer.WriteLine("103,Amit,78.25");
            }

            Console.WriteLine("CSV file created successfully at " + path);
        }
    }
}

🧾 Output File (students.csv)
RollNo,Name,Marks
101,Rahul,89.5
102,Priya,92.0
103,Amit,78.25

✅ Example 2: Read Data from CSV File
using System;
using System.IO;

namespace CSVExample
{
    internal class ReadCSV
    {
        static void Main(string[] args)
        {
            string path = "d:\\students.csv";

            if (File.Exists(path))
            {
                string[] lines = File.ReadAllLines(path);

                Console.WriteLine("Reading data from CSV:\n");

                // Skip header (start from 1)
                for (int i = 1; i < lines.Length; i++)
                {
                    string[] data = lines[i].Split(',');

                    Console.WriteLine("Roll No: " + data[0]);
                    Console.WriteLine("Name   : " + data[1]);
                    Console.WriteLine("Marks  : " + data[2]);
                    Console.WriteLine("-------------------------");
                }
            }
            else
            {
                Console.WriteLine("File not found!");
            }
        }
    }
}

🧠 Excel File Formats

.xls → older Excel format (Excel 97–2003)

.xlsx → modern Excel format (Excel 2007+)

We’ll use .xlsx — it’s more common and supported by modern libraries.

✅ Option 1: Using ClosedXML (Recommended)

ClosedXML is a very popular and easy-to-use library for Excel operations.
👉 You can install it using NuGet:

Install-Package ClosedXML

📝 Example: Write Data to Excel File
using System;
using ClosedXML.Excel;

namespace ExcelExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = "d:\\students.xlsx";

            // Create workbook and worksheet
            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("StudentData");

                // Add headers
                worksheet.Cell(1, 1).Value = "Roll No";
                worksheet.Cell(1, 2).Value = "Name";
                worksheet.Cell(1, 3).Value = "Marks";

                // Add data
                worksheet.Cell(2, 1).Value = 101;
                worksheet.Cell(2, 2).Value = "Rahul";
                worksheet.Cell(2, 3).Value = 89.5;

                worksheet.Cell(3, 1).Value = 102;
                worksheet.Cell(3, 2).Value = "Priya";
                worksheet.Cell(3, 3).Value = 92.0;

                worksheet.Cell(4, 1).Value = 103;
                worksheet.Cell(4, 2).Value = "Amit";
                worksheet.Cell(4, 3).Value = 78.25;

                // Save file
                workbook.SaveAs(filePath);
                Console.WriteLine("Excel file created successfully at " + filePath);
            }
        }
    }
}

📖 Example: Read Data from Excel File
using System;
using ClosedXML.Excel;

namespace ExcelExample
{
    internal class ReadExcel
    {
        static void Main(string[] args)
        {
            string filePath = "d:\\students.xlsx";

            using (var workbook = new XLWorkbook(filePath))
            {
                var worksheet = workbook.Worksheet("StudentData");

                Console.WriteLine("Reading data from Excel:\n");

                // Skip header row (start from 2)
                int row = 2;
                while (!worksheet.Cell(row, 1).IsEmpty())
                {
                    int rollNo = worksheet.Cell(row, 1).GetValue<int>();
                    string name = worksheet.Cell(row, 2).GetValue<string>();
                    double marks = worksheet.Cell(row, 3).GetValue<double>();

                    Console.WriteLine($"RollNo: {rollNo}, Name: {name}, Marks: {marks}");
                    row++;
                }
            }
        }
    }
}
                               

Post a Comment

0 Comments