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.

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.

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