Skip to main content

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.

                               

Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...