
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create String from File Contents in C#
Introduction
Let us see how to create a C# program to create a string from the contents of a file. The string is an integral part of file handling. A string in C# is a series of letters. Like, "TutorialsPoint" is a string containing 't' 'u' 't' 'o' 'r' 'i' 'a' 'l' 's' 'p' 'o' 'i' 'n' 't' as characters. We use the string keyword to create a string.
File handling or file management in layman's terms the various processes such as making the file, reading from it, writing to it, appending it, and so on. The viewing and writing of files are the two most common operations in file management. The System.IO category in C# includes classes that deal with input and output streams.
As string creation is a crucial part of file handling. Here, the complete text is read and then transferred into the string. Well, there are two ways to create the string from the contents of the file. In the upcoming section, we will see both ways to read the contents of the file and transfer it into the string.
1. File.ReadAllText() Method
This is the first method to read all the contents of the file in a string. Here, File.ReadAllText() method is used. File.ReadAllText() reads all the content from the file and then it transfers the content into the string. Encoding of the file is determined automatically by the File.ReadAllText(). The encoding of the file is determined by its overloaded version. Well, defining Encoding, it is a numbering system that allows a numerical value to each written character in a character set. Characters from the letters, numerals, and other symbols can all be found in a character set.
While executing the command to open the file, if the source file is not found or any other type of I/O error occurs then an IOException is thrown. This happens if any problems come in the Input and Output of the file.
Algorithm
The algorithm below will give a step-by-step procedure to create a String from the contents of the file by using File.ReadAllText() method.
For example, if we have to read all the content from the file and then transfer the content to a string then we should provide its precise algorithm as follows ?
Step 1 ? Create an instance fileName to read from a file and provide an address to it.
Step 2 ? Reading and displaying text lines from the file by using File.ReadAllText and store it in text.
Step 3 ? By using catch we try to catch the error if any error occurs.
Step 4 ? If there is any error then it is stored in e and then displayed.
Step 5 ? By using Console.Readkey() we halt the execution of the program at the end.
Example
Following is the snippet of the code that shows the example.
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Example { public static void Main() { string fileName = @"C:\some\path\file.txt"; try { // Display the lines that are read from the file string text = File.ReadAllText(fileName); Console.WriteLine(text); } catch (Exception e) { // Displays the error on the screen. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } Console.ReadKey(); } }
Output
Input is completed
Here, firstly the path is provided to a string which is in turn passed and opened from the address. Then the entire content is copied to the string that is created. If the file could not be opened that an error occurs and the mess is shown on the screen. There is another way to do so by using SteamReader class. Let us that too.
2. SteamReader.ReadToEnd() Method
The alternative solution is also there to File.ReadAllText() is SteamReader.ReadToEnd().This also reads the complete file in one go and then copies the content to the string. File.OpenText method is used by Steam.Reader for this operation. Then ReadToEnd() method reads the complete file that is mentioned by the user in one go. After the work of the SteamReader object is finished then the Dispose() method is automatically invoked just like the Destructor() and this flushes/clears the stream.
Algorithm
The algorithm below will give a step-by-step procedure to create a String from the contents of the file by using SteamReader.ReadToEnd() method.
For example, if we have to read all the content from the file and then transfer the content to a string then we should provide its precise algorithm as follows ?
Step 1 ? Create an instance fileName to read from a file and provide an address to it.
Step 2 ? Create an instance of StreamReader for reading contents from the file.
Step 3 ? Read the text lines from the file by using SteamReader.ReadToEnd() and store it in the variable text.
Step 4 ? Now we write the text data by using Console.Writeline().
Step 5 ? By using Console.Readkey() we halt the execution of the program at the end.
Now, let's see the code.
Example
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Example { public static void Main() { string fileName = @"C:\some\path\file.txt"; // Creating an instance strRead of StreamReader for reading text from the given file using (StreamReader strRead = File.OpenText(fileName)) { string text = strRead.ReadToEnd(); Console.WriteLine(text); } Console.ReadKey(); } }
Output
Input is completed
When we use File.OpenText() it opens an existing UTF-8 encoded file by default. To access a file with a different character encoding, the StreamReader class constructor is needed to be used which accepts an alternative character encoding.
The given example creates a new ASCII StreamReader from a file with byte order mark recognition set to true.
Example
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Example { public static void Main() { string fileName = @"C:\some\path\file.txt"; // Creating an instance strRead of StreamReader for reading text from the given file using (StreamReader strRead = new StreamReader(fileName, Encoding.ASCII, true)) { string text = strRead.ReadToEnd(); Console.WriteLine(text); } Console.ReadKey(); } }
Output
Input is completed
Time Complexity
In both the codes if we see there is no loop as we are just creating an instance to read the file. And then all the content of the file is copied to the string. For File.ReadAllText() method the time complexity stands at O(1). Similarly, in SteamReader.ReadToEnd() method the time complexity stands at O(1).
Conclusion
In this article, we have extensively discussed the C# Program to Create string from Contents of a File. Firstly, we talked about the string and then the different types of ways to read the complete contents of the file into the string. We hope that this article has helped you enhance your knowledge regarding C#.