In Web Development
0
325

Stream: file is a collection of data storage in a memory with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.

The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream.

Input Stream

We are using input stream class for reading data from a file (read operation). It is responsible for accepting data in the form of bytes, streams, binary data, or strings from input devices such as keyboards, mouse, or other media.

Output Stream

The output stream is used for writing into the file (write operation). The output part of the system displays processed data through devices such as monitors or printers.

C# Input/Output Stream Classes

The System.IO namespace has multiple classes for performing various operations with files, following are some important classes of  System.IO namespace.System.IO.

The stream is an abstract class that provides standard methods to transfer bytes to the source. Stream Classes that need to read and write bytes from a particular source must implement the Stream classes.

  • Directory
  • DirectoryInfo
  • DriveInfo
  • File
  • FileInfo
  • Path
  • FileStream
  • MemoryStream
  • buffered stream
  • TextWriter
  • TextReader
  • BinaryWriter
  • BinaryReader
  • StreamWriter
  • StreamReader
  • StringWriter
  • StringReader

Directory

The Directory class is used for manipulating directories & subdirectories. It exposes many static methods for moving, copying, and deleting directories. Following is the sample code for Directory class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
if (Directory.Exists("c:\\testDir1"))
{
//shows message if testdir1 exist
Console.WriteLine("Directory 'testDir' Exist ");
}
else
{
//create the directory testDir1
Directory.CreateDirectory("c:\\testDir1");
Console.WriteLine("testDir1 created ! ");
//create the directory testDir2
Directory.CreateDirectory("c:\\testDir1\\testDir2");
Console.WriteLine("testDir2 created ! ");
//move the directory testDir2 as testDir in c:\
Directory.Move("c:\\testDir1\\testDir2", "c:\\testDir");
Console.WriteLine("testDir2 moved ");
//delete the directory testDir1
Directory.Delete("c:\\testDir1");
Console.WriteLine("testDir1 deleted ");
}
Console.ReadKey();
}
}
}

DirectoryInfo

The DirectoryInfo class is used to retrieve directory & subdirectory related information. Below is the sample code for DirectoryInfo class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
String path = string.Empty;
DirectoryInfo f1;
DirectoryInfo f2;
//
// Create Method
path = @"C:\Users\abc\MyTestFile1.txt";
f1 = new DirectoryInfo(path);
f1.Create();
{
Console.WriteLine("Directory has been created");
}
//
// CreateSubdirectory Method
path = @"C:\Users\abc\MyTestFile1.txt";
f1 = new DirectoryInfo(path);
DirectoryInfo dis = f1.CreateSubdirectory("hellotest");
{
Console.WriteLine("Directory has been created");
}
//
// MoveTo Method
path = @"C:\Users\abc\MyTestFile1.txt";
string path1 = @"C:\Users\abc\NewFile1.txt";
f1 = new DirectoryInfo(path);
f2 = new DirectoryInfo(path1);
f1.MoveTo(path1);
{
Console.WriteLine("Directory has been Moved");
}
//
// Delete Method
path = @"C:\Users\abc\NewFile1.txt";
f1 = new DirectoryInfo(path);
f1.Delete();
{
Console.WriteLine("Directory has been deleted");
}
//
// GetDirectories method
try
{
DirectoryInfo di = new DirectoryInfo(@"C:\Users\abc\newFile\");
DirectoryInfo[] dir1 = di.GetDirectories();
Console.WriteLine("The number of directories containing is {0}.", dir1.Length);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
//
// GetFiles method
DirectoryInfo di2 = new DirectoryInfo(@"C:\Users\abc\newfile");
DirectoryInfo[] dirs = di2.GetDirectories();
foreach (DirectoryInfo diNext in dirs)
{
Console.WriteLine("The number of files in {0} is {1}", diNext, diNext.GetFiles().Length);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

DriveInfo

The DriveInfo class is used to retrieve drive-related information. Below is the sample code for DriveInfo class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
DriveInfo info = new DriveInfo("C");
//
// Print sizes.
Console.WriteLine(info.AvailableFreeSpace);
Console.WriteLine(info.TotalFreeSpace);
Console.WriteLine(info.TotalSize);
Console.WriteLine();
//
// Format and type.
Console.WriteLine(info.DriveFormat);
Console.WriteLine(info.DriveType);
Console.WriteLine();
//
// Name and directories.
Console.WriteLine(info.Name);
Console.WriteLine(info.RootDirectory);
Console.WriteLine(info.VolumeLabel);
Console.WriteLine();
//
// Ready.
Console.WriteLine(info.IsReady);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

File

File class is used to get file-related information. Below is the sample code for File class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
if (File.Exists("C:\\Users\\abc\\testFile.txt"))
{
//shows message if testFile exist
Console.WriteLine("File 'testFile' Exist ");
}
else
{
//create the file testFile.txt
File.Create("C:\\Users\\abc\\testFile.txt");
Console.WriteLine("File 'testFile' created ");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

FileInfo

FileInfo class is used to perform file-related operations like create, delete, copy, and move file etc. Below is the sample code for FileInfo class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
FileInfo fi;
FileInfo fi1;
FileInfo fi2;
string path;
string path2;
string s;
FileStream fs;
StreamWriter sw;
// StreamReader sr;
//
// Create Method
fi = new FileInfo(@"C:\Users\abc\MyTestFile7.txt");
fs = fi.Create();
Console.WriteLine("File has been created");
fs.Close();
//
//CreateText Method
fi = new FileInfo(@"C:\Users\abc\MyTestFilecreatetext1.txt");
sw = fi.CreateText();
sw.WriteLine("hello");
Console.WriteLine("File has been created with text");
//
//Delete Method
fi = new FileInfo(@"C:\Users\abc\MyTestFilecreatetext.txt");
fi.Delete();
Console.WriteLine("File has been deleted");
fs.Close();
//
//CreateText Method
path = @"C:\Users\abc\MyTestFile7.txt";
path2 = @"C:\Users\abc\NewFile.txt";
fi1 = new FileInfo(path);
fi2 = new FileInfo(path2);
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2);
//
//MoveTo Method
path = @"C:\Users\abc\NewFile.txt";
path2 = @"E:\NewFile1.txt";
fi1 = new FileInfo(path);
fi2 = new FileInfo(path2);
fi1.MoveTo(path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
//
//ApendText Method
fi = new FileInfo(@"E:\NewFile1.txt");
sw = fi.AppendText();
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
Console.WriteLine("File has been appended");
sw.Close();
//
//Opentext Method
fi = new FileInfo(@"E:\NewFile1.txt");
StreamReader sr = fi.OpenText();
s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

Path

The Path Class is used to perform operations on String instances that contain file or directory path information. Below is the sample code for Path class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.

try
{
string tmpPath = "Text.txt";
string fileExtension = Path.GetExtension(tmpPath);
string filename = Path.GetFileName(tmpPath);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(tmpPath);
string rootPath = Path.GetPathRoot(tmpPath);
string directory = Path.GetDirectoryName(tmpPath);
string fullPath = Path.GetFullPath(tmpPath);
Console.WriteLine(fullPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Console.ReadKey();
}
}
}

FileStream

The FileStream class is derived from abstract class Stream which is in the System.IO namespace.  Below is the sample code for FileStream class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{

FileStream file = new FileStream("text.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);

for (int i = 0; i < 20; i++)

{
file.WriteByte((byte)i);
}
file.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(file.ReadByte() + " ");
}
file.Close();
Console.ReadKey();

}
}
}

MemoryStream

MemoryStream class and its members are used to read data in the memory stream.  Below is the sample code for MemoryStream class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
int count;
byte[] byteArray;
char[] charArray;
UnicodeEncoding uniEncoding = new UnicodeEncoding();
byte[] firstString = uniEncoding.GetBytes("Invalid file path characters are: ");
byte[] secondString = uniEncoding.GetBytes(Path.GetInvalidPathChars());
using (MemoryStream memStream = new MemoryStream(100))
{
memStream.Write(firstString, 0, firstString.Length);
count = 0;
while (count < secondString.Length)
{
memStream.WriteByte(secondString[count++]);
}
Console.WriteLine("Capacity = {0}, Length = {1}, Position = {2}\n",
memStream.Capacity.ToString(),
memStream.Length.ToString(),
memStream.Position.ToString());
memStream.Seek(0, SeekOrigin.Begin);
byteArray = new byte[memStream.Length];
count = memStream.Read(byteArray, 0, 20);
while (count < memStream.Length)
{
byteArray[count++] = Convert.ToByte(memStream.ReadByte());
}
charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)];
uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
Console.WriteLine(charArray);
Console.Read();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

BufferedStream

As we know that Buffered streams are used to provide better read/write performance.We use this class either read or write data but it can’t be used to perform both read and write operations together. Below is the sample code for BufferedStream class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
try
{
var t1 = Stopwatch.StartNew();
using (MemoryStream memory = new MemoryStream())
using (BufferedStream stream = new BufferedStream(memory))
{
for (int i = 0; i < 5000000; i++)
{
stream.WriteByte(5);
}
}
t1.Stop();
Console.WriteLine("Bufferedstream time : " + t1.Elapsed.TotalMilliseconds);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

TextWriter

Textwriter is another way to write a file.  The StreamWriter classes are derived from TextWriter classes.  Below is the sample code for TextWriter class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
TextWriter writeFile = new StreamWriter("text.txt");
writeFile.WriteLine("csharp.net-informations.com");
writeFile.Flush();
writeFile.Close();
writeFile = null;
}
catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

TextReader

We have another class Textreader for reading a file.  It represents a reader that can read a sequential series of characters.  Below is the sample code for TextReader class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
string line = null;
TextReader readFile = new StreamReader("text.txt");
while (true)
{
line = readFile.ReadLine();
if (line != null)
{
Console.WriteLine(line);
}
}
readFile.Close();
readFile = null;
}
catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

BinaryWriter

We use C# BinaryWriter Class for writing primitive types as a binary value in a specific encoding stream. Its Object works with Stream Objects that provide access to the underlying bytes.  Below is the sample code for BinaryWriter class. Create a console application and use the following code for better understanding.

Example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
FileStream writeStream;
try
{
writeStream = new FileStream("Text.txt", FileMode.Create);
BinaryWriter writeBinay = new BinaryWriter(writeStream);
writeBinay.Write("CSharp.net-informations.com binary writer test");
writeBinay.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

BinaryReader

We use C# BinaryReader class for reading primitive types as a binary value in a specific encoding stream. Its Object works with Stream Objects that provide access to the underlying bytes. Below is the sample code for BinaryReader class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
FileStream readStream;
string msg = null;
try
{
readStream = new FileStream("Text.txt", FileMode.Open);
BinaryReader readBinary = new BinaryReader(readStream);
msg = readBinary.ReadString();
Console.WriteLine(msg);
readStream.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

StreamReader

We use streamReader Class for reading character-based data, Its found under System.IO namespace.  Below is the sample code for StreamReader class. Create a console application and use the following code for better understanding.

Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "StreamReader";
using (StreamReader sr = File.OpenText(@"C:\Users\abc\testFile.txt"))
{
string tables = null;
while ((tables = sr.ReadLine()) != null)
{
Console.WriteLine("{0}", tables);
}
Console.WriteLine("Table Printed.");
}
Console.ForegroundColor = ConsoleColor.Gray;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

StreamWriter

We use streamWriter Class for writing character-based data, Its found under System.IO namespace. Below is the sample code for SteramWriter class. Create a console application and use the following code for better understanding.

Example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "Stream Writer";
using (StreamWriter sw = File.CreateText(@"C:\Users\abc\testFile.txt"))
{
sw.WriteLine("Please find the below generated table of 1 to 10");
sw.WriteLine("");
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
sw.WriteLine("{0}x{1}= {2}", i, j, (i * j));
}
sw.WriteLine("==============");
}
Console.WriteLine("Table successfully written on file.");
}
Console.ForegroundColor = ConsoleColor.Gray;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

StringReader

We use StringReader class for reading a string from the string, It’s derived from TextReader class and also enables you to read a string synchronously or asynchronously. Below is the sample code for StringReader class. Create a console application and use the following code for better understanding.

Example : 

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
// Example string data
string text = @"You are reading this article at completecsharptutorial.com";
using (StringReader reader = new StringReader(text))
{
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
Console.WriteLine("Line {0}: {1}", count, line);
}
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

StringWriter

We use StringWriter class for manipulating a string, Its derived from TextWriter class.  Below is the sample code for StringWriter class. Create a console application and use the following code for better understanding.


Example : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace File_Input_Output_Stream
{
class Program
{
static void Main(string[] args)
{
//Default created file location is in debug folder.
try
{
// Example string data
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
string name = "Anaam Ahmad";
sw.WriteLine("Name : " + name);
sw.Flush();
sw.Close();
Console.WriteLine(sb);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}

Summary

I hope, this article would help you to understand about System.IO namespace. The role of System.IO is very important in c#. It helps you to read, write and manipulate any type of data. Its also helps you to retrieve information about directory, file, memory, drive, etc.

RECOMMENDED POSTS

Start typing and press Enter to search