File,Stream I/O and Garbage Collection
This article will cover File,Stream I/O and Garbage Collection with very easy examples
File
A file is an ordered collection of the bytes of data with proper name and physical existence.A file is stored on the disk in a directory having specific path.
The file can also be stored in other storage media such as tapes, cd, dvd, usb drive etc.
Stream
Stream is the the way to read and write bytes of the data from different storage mediums.
The namespace System.IO contains several objects which perform reading and writing operations on streams and files.
Synchronous and Asynchronous Operations
As System.IO performs both Synchronous and Asynchronous operations on both files and streams,we have to understand what are these operations .
A synchronous operation prevents us from doing any other thing when till the currrent operation(s) is performing its task.
On the other hand , an asynchronous operation let us perform some other functions if the current operation is taking time.
For the convenience, we have to show through the animation that a particular operation is in progress.
Check the following link to see the details about File Class and the members which this class uses to read,write,delete,move,setting path etc
I want to discuss something regarding the “using block” in C# code.
Purpose and Use of using keyword
The using keyword is used to define block of code with the guarantee that anything present within the body of using will be dispose off (even if the exception has been thrown).
The use of this keyword is excellent as it cleans the garbage in the memory automatically by disposing which implements IDisposable interface.
No need to worry about the interface,just skim through the tutorial to clarify the concept.
How to Program with using keyword:
Example
using System;
using System.IO;
class CreateFile
{
public static void Main()
{
/*
* the file as you wish
*
*
*/
string directoryPath = @”E:CreatedFile.txt”;
/*
* Check to see whether the file exists in the specified path/directory.
* If the file doesn’t exist,then create a file with the File.CreateText()
* static method for StreamWriter object.
* in a particular path and write to the file with StreamWriter object
* for writing the characters to the stream in a particular encoding
* here we have used a block of using which creates the file and writes to it.
*using is also helpful for an object to remain alive in the using block of code
* rather than reinitializing it time and time
*/
if (!File.Exists(directoryPath))
{
using (StreamWriter writer = File.CreateText(directoryPath))
{
// The WriteLine method writes a string to the stream
writer.WriteLine(“My “);
writer.WriteLine(“name “);
writer.WriteLine(“is Don”);
}
}
// The StreamReader object reads the bytes of character from Stream in a particular encoding
using (StreamReader reader = File.OpenText(directoryPath))
{
/*we used string str for temporary storage of the lines read
* by StreamReader
*/
string str = “”;
//iterate till there is no character left
while ((str = reader.ReadLine()) != null)
{
Console.WriteLine(str);
}
}
}
}
Your file will be created in E: (or whatever drive of the choice).Take care about creating it in the primary partition because of the security issues .Sometimes,the file is not allowed to be created in the same drive where your Windows is installed
Output
My
name
is Don
Basic File Operations
The given example will show you everything you need to perform basic file operations
Example
using System;
using System.IO;
public class FileOperations
{
/* Always check for the security constraints before executing these types of program
* make get the full allowed permission to access the drive(s)*/
static void Main()
{
/*Create a new folder ‘Src’ in drive E: if the suggested
*name doesn’t exists
* */
if (!Directory.Exists(@”E:Src”))
{
Directory.CreateDirectory(@”E:Src”);
if (!File.Exists(@”E:SrcSrc.txt”))
{
File.Create(@”E:SrcSrc.txt”);
Console.WriteLine(@”File created in E:Src”);
/* You have to write the code here in order to write something to
created file with StreamWriter discussed previously
*/
}
}
if (!Directory.Exists(@”D:Dest”))
{
Directory.CreateDirectory(@”D:Dest”);
if (!File.Exists(@”D:DestDest.txt”))
{
File.Create(@”D:DestDest.txt”);
Console.WriteLine(@”File created in D:Dest”);
}
/* You have to write the code here in order to write something to
created file with StreamWriter discussed previously
*/
}
// Copy the file from source to destination
File.Copy(@”E:SrcSrc.txt”, @”D:DestDest.txt”, true);
//Explore Moving and Deleting by yourself
Console.WriteLine(“File Copied”);
}
}
Run the program without debugging(if you are using Visual studio ).Or run the program with online C# compiler
You can also compile through command prompt,by writing the code on the notepad+,provided that, you have .Net framework installed.The procedure is here
In order to see the list of common I/O Tasks,you have to check the following microsoft link.
Binary Reader and Writer
The Binary Reader and Writer are used to perform operation on big files.Binary reader does not remember file location when the operation is incomplete.
class myBinaryOperations
{
static void Main()
{
// taking an array of 10 elements to write to the stream
byte[] myArray = new byte[10]{1,2,3,4,5,6,7,8,9,10};
/*writes primitive types in a binary to stream and supports encoding
MemoryStream() initializes System.IO.MemoryStream class
with an expandable capacity initialized to zero */
BinaryWriter myWriter = new BinaryWriter(new MemoryStream());
// Write the data to the stream.
Console.WriteLine(“Writing the data.”);
myWriter.Write(myArray);
Thread.Sleep(2000);
// Get the stream from BinaryWriter
BinaryReader myReader = new BinaryReader(myWriter.BaseStream);
// 0 indicates the beginning of the stream
//so the value of the BaseStream’s position has been set to 0
myReader.BaseStream.Position = 0;
Console.WriteLine(“nThe Data has been written successfully “);
Console.ReadKey();
}
}
Output