File Handlings

File Handling in C#

Streams - When you open a file for reading or writing, it becomes stream. Stream is a sequence of bytes traveling from a source to a destination over a communication path.

The two basic streams are input and output streams. Input stream is used to read and output stream is used to write.

C# uses the [File class] as a primary method to handle Files. Which has multiple methods to create, save, open, copy, move, delete, or check the existence of a file.

System.IO namespace contains various classes for file handling.

Class Name

Description

FileStream

It is used to read from and write to any location within a file

BinaryReader

It is used to read primitive data types from a binary stream

BinaryWriter

It is used to write primitive data types in binary format

StreamReader

It is used to read characters from a byte Stream

StreamWriter

It is used to write characters to a stream.

StringReader

It is used to read from a string buffer

StringWriter

It is used to write into a string buffer

StreamWriter Class

Inherited from TextWriter Class which can write a series of characters.

It is used to read characters from a byte Stream -> Paired with FileStream.

Methods

Description

Close

Closes the current StreamWriter object and the underlying stream

Flush

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream

Write

Writes to the stream

WriteLine

Writes data specified by the overloaded parameters, followed by end of line

using System;  
using System.Text;  
using System.IO;  
namespace FileWriting_SW  
{  
    class Program  
    {  
        class FileWrite  
        {  
            public void WriteData()  
            {  
                FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write);  
                StreamWriter sw = new StreamWriter(fs);  
                Console.WriteLine("Enter the text which you want to write to the file");  
                string str = Console.ReadLine();  
                sw.WriteLine(str);  
                sw.Flush();  
                sw.Close();  
                fs.Close();  
            }  
        }  
        static void Main(string[] args)  
        {  
            FileWrite wr = new FileWrite();  
            wr.WriteData();  
        }  
    }  
}  

References

https://www.c-sharpcorner.com/UploadFile/puranindia/file-handling-in-C-Sharp/

Last updated