Posts

Showing posts from February, 2024

File in C#

In   C# , the   File   class from the   System.IO   namespace provides static methods for various file operations. Let’s explore some key aspects of working with files in C#: Creating a File : To create a new file, you can use the  File.CreateText(path)  method. Here’s an example that checks if a file exists, and if not, creates a new file and writes to it: C# using System; using System.IO; class Test { public static void Main () { string path = @"c:\temp\MyTest.txt" ; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine( "Hello" ); sw.WriteLine( "And" ); sw.WriteLine( "Welcome" ); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { string s; while ((s ...

Stream in C#

A   stream   is an object used to transfer data. There is a generic stream class   System.IO.Stream , from which all other stream classes in .NET are derived. The   Stream   class deals with bytes. The concrete stream classes are used to deal with other types of data than bytes. For example: The  FileStream  class is used when the outside source is a file MemoryStream  is used to store data in memory System.Net.Sockets.NetworkStream  handles network data Reader/writer streams such as  StreamReader  and  StreamWriter  are not streams - they are not derived from  System.IO.Stream , they are designed to help to write and read data from and to stream!