C# File Operations - GR Software Solutions - Bangalore

C# File Operations


C# has a wide array of file operations. These operations include opening a file, reading or writing to a file.
There can be an instances wherein you want to work with files directly, in which case you would use the file operations available in C#.

3.    Appending – This operation also involves writing information to a file. The only difference is that the existing data in a file is not overwritten. The new data to be written is added at the end of the file.
This tutorial focuses on how to work with files in C#.
In this tutorial, you will learn-
·        Basic File I/O Commands
·        Serialization

Basic File I/O Commands

C# and .Net has the ability to work with files with the help of several File I/O commands. Let's have a look at some of these commands. For our example, we will assume that we have a file in the D drive called Example.txt.
The file will be a simple text file and have 2 lines as shown below
  • GR - .Net
  • GR-C#
For our example, we will create a simple Console application and work with our File I/O commands. The console application is the basic one which was created in the earlier chapters. In the console application, all code is written to the Program.cs file.
1.    File.Exists – The File exists method is used to check if a particular file exists. So now let's see the code which can be used to check if our Example.txt file actually exists or not. Enter the below code in the program.cs file.

Code Explanation:-
1.    First, we are setting a string variable with the path to our Example.txt file.
2.    Next, we use the File.Exists method to check if the file really exists or not. If the File exists, a true value will be returned.
3.    If we get a true value and the file does exist, then we write the message "File Exists" to the console.
When the above code is set, and the project is executed using Visual Studio, you will get the below output.
Output:-

From the above output, you can clearly see that the File.Exists command was executed successfully, and the correct message was displayed in the console window.
2.    File.ReadAlllines – The method is used to read all the lines one by one in a file. The lines are then stored in a string array variable. Let's look at an example. Enter the below code in the program.cs file.

Code Explanation:-
1.    First, we are declaring a string array variable. This will be used to store the result which will be returned by the File.ReadAllLines method.
2.    Next, we use the File.ReadAllLines method to read all the lines from our text file. The result is then passed to the lines variable.
3.    Since we know that our file contains only 2 lines, we can access the value of the array variables via the lines[0] and lines[1] command.
When the above code is set, and the project is run using Visual Studio, you will get the below output.
Output:-

From the output, you can clearly see that the File.ReadAllLines command returned both the lines from our file Example.txt
3.    File.ReadAllText – This method is used to read all the lines in a file at once. The lines are then stored in a string variable. Let's look at an example. Enter the below code in the program.cs file.

Code Explanation:-
1.    First, we are declaring a string variable called Lines. This will be used to store the result which will be returned by the File.ReadAllText method.
2.    Next, we use the File.ReadAllText method to read all the lines from our text file. The result is then passed to the lines variable.
3.    We can directly use the Console.Writeline method to display the value of the Lines variable.
When the above code is set, and the project is run using Visual Studio, you will get the below output.
Output:-

From the output, you can clearly see that the File.ReadAlltext command returned both the lines from our file Example.txt
4.    File.Copy – The method is used to make a copy of an existing file. Let's look at an example. Enter the below code in the program.cs file.

Code Explanation:-
1.    First, we are declaring a string variable called path. This will be the location of our Example.txt file. This file will be the source file used for the copy operation.
2.    Next, we are declaring a string variable called copypath. This will be the location of a new file called ExampleNew.txt file. This will be the destination file in which the contents will be written from the source file Example.txt.
3.    We then call the File.Copy method to copy the file Example.txt file to the file ExampleNew.txt.
When the above code is set, and the project is run using Visual Studio, the file Example.txt will be copied to ExampleNew.txt.
5.    File.Delete – The method is used to delete an existing file. Let's look at an example. Enter the below code in the program.cs file.

Code Explanation:-
1.    First, we are declaring a string variable called path. This will be the location of our Example.txt file. This is the file which will be deleted.
2.    Next, we are calling the File.Delete method to delete the file.
When the above code is set, and the project is run using Visual Studio, the file Example.txt will be deleted from the D drive.

Streams – Reading and Writing to files

In C# file operations, normally streams are used to read and write to files. A stream is an additional layer created between an application and a file. The stream is used to ensure smooth read and write operations to the file.
Streams are normally used when reading data from large files. By using streams, the data from large files in broken down into small chunks and sent to the stream. These chunks of data can then be read from the application.
The reason for breaking it down into small chunks is because of the performance impact of reading a big file at one shot. If you were to read the data from say, a 100 MB file at one shot, your application could just hang and become unstable. The best approach is then to use streams to break the file down into manageable chunks.
So when a write operation is carried out on the file, the data to be written, is first written to the stream. From the stream, the data is then written to the file. The same goes for the read operation. In the read operation, data is first transferred from the file to the stream. The data is then read from the application via the stream. Let's look at an example of how we can read and write using streams.
For our example, we will assume that we have a file in the D drive called Example.txt. The file will be a simple text file and have 2 lines as shown below
  • GR- .Net
  • GR-C#
For our example, we will create a simple Console application and work with File streams
1.    Stream Reader – The stream reader is used to read data from a file using streams. The data from the file is first read into the stream. Thereafter the application reads the data from the stream.
Let's look at an example of how we can use streams for reading data from a file. Enter the below code in the program.cs file.

Code Explanation:-
1.    First, we are declaring a stream reader object. The stream reader object is used in C# to define a stream from the file to the application. The data will be pushed from the file to the stream whenever data is read from the file. The File.OpenText is used to open the file "Example.txt" in read-only mode. The handler to the file is then sent to the stream reader object.
2.    Next, we are defining a temporary variable 's' which will be used to read all the data from the file.
3.    We then use the stream reader method ReadLine to read each line from the stream buffer. When we perform this operation, each line will be first transferred from the file to the buffer. Then the string line will be transferred from the buffer to the variable 's'. We then write the contents of the string 's' to the console.
When the above code is set, and the projectis run using Visual Studio, you will get the below output.
Output:-

From the output, you can clearly see that the Stream Reader read both the lines from the file. Finally, the lines of the string read from the stream were sent to the Console.
2.    Stream Writer – The stream writer is used to write data to a file using streams. The data from the application is first written into the stream. Thereafter the stream writes the data to the file. Let's look at an example of how we can use streams for writing data from a file. Enter the below code in the program.cs file.

Code Explanation:-
1.    First, we are declaring a stream writer object. The stream writer object is used in C# to define a stream. The stream is then used to write data from the application to the file. The data will be pushed from the application to the stream whenever data needs to be written. The File.AppendText command is used to open the file "Example.txt" in an append mode. The handler to the file is then sent to the stream writer object.
2.    We are using the stream write method Writeline to write the line "GR– ASP.Net" to the stream. From the stream, the line will then be written to the file.
3.    We then close the stream writer after writing to the file. It's normally a good practice to close file handlers when the file is no longer required for writing purposes.
4.    Finally, we are reading the contents of the file again and writing it to the console log. This is to check as to whether the line was really written to the file.
When the above code is set, and the project is run using Visual Studio, you will get the below output.
Output:-

From the output, you can see that the line "GR– ASP.Net" was added to the file successfully. All the 3 lines of text can be clearly seen in the console.

C# Serialization

The concept of Serialization and deserialization is used whenever data pertaining to objects have to be sent from one application to another. Serialization is used to export application data into a file. The destination application then uses deserialization to extract the data from the application for further use.
Serialization is a concept in which C# class objects are written or serialized to files. Let' say you had a C# class called Tutorial. And the class has 2 properties of ID and Tutorials name.
Serializing can be used to directly write the data properties of the Tutorial class to a file. Deserialization is used to read the data from the file and construct the Tutorial object again.
Let's look at an example of how we can achieve this.
In our example, we are going to perform the below high-level steps in the code
1.    Create a class called Tutorial which has 2 properties , namely ID and Name
2.    We will then create an object from the class and assign a value of "1" to the ID property and a value of ".Net" to the name property.
3.    We will then use serialization to serialize the above object to a file called Example.txt
4.    Finally, we will use deserialization to deserialize the object from the file and display the values in the Console.
Enter the below code in the program.cs file of the console application.
Step 1) The first step is to add the class which will be used for serialization

Code Explanation:-
1.    The class which needs to be serialized needs to have the [Serializable] attribute. This is a keyword in C#. This keyword is then attached to the Tutorial class. If you don't mention this attribute, you will get an error when you try to serialize the class.
2.    Next is the definition of the class which will be serialized. Here we are defining a class called "Tutorial" and providing 2 properties, one is "ID" and the other is "Name."
Step 2) In this step, first we will create the object of the Tutorial class and serialize it to the file called Example.txt

Code Explanation:-
1.    First, we create an object of the Tutorial class. We then assign the value of "1" to ID and ".net" to the name property.
2.    We then use the formatter class which is used to serialize or convert the object to a binary format. The data in the file in serialization is done in binary format. Next, we create a file stream object. The file stream object is used to open the file Example.txt for writing purposes. The keywords FileMode.Create and FileMode.Write is used to specifically mention that the file should be opened for writing purposes.
3.    Finally, we use the Serialize method to transfer the binary data to the file. We then close the stream, since the write operation is complete.
Step 3) Finally to ensure that the data is present in the file, we use deserialization to deserialize the object from the file.

Code Explanation:-
1.    We create the object "stream" to open the file Example.txt in read only mode.
2.    We then use the formatter class which is used to deserialize the object, which is stored in the Example.txt file. The object returned is set to the object objnew.
3.    Finally, we display the properties of the object "objnew" to the console using the "ID" and "name" properties.
When the above code is set, and the project is run using Visual Studio, you will get the below output.
Output:-

You can see from the above output that the values from the file were deserialized properly and displayed in the console.
Summary
  • C# has a number of File operations which can be performed on files. Most of these operations are part of the class File.
  • If you want to read data from a file, you can use the File.ReadAlltext or File.ReadAllLines methods.
  • Streams are used as an intermediate level between the application and the file.
    • A StreamReader is used whenever data is required to be read from a file.
    • A Streamwriter is used whenever data needs to be written to a file.
  • Serialization is used to write class objects to files. De- Serialization is used to recover the objects from the file.






Reference:

Comments

Popular posts from this blog

Visual Basic 6 (VB6) Operators

C# Delegates simple example in .NET

Control Structures In Visual Basic 6.0