C# Read File

王林
Release: 2024-09-03 15:05:22
Original
804 people have browsed it

Performing file operations is an integral part of the programmer’s life and all the programming languages provide various libraries or functions to achieve the same. The same can be done in C# using the methods available in the File class provider. Generally reading from a file is performed using the two methods ReadAllText(file) and ReadAllLines(file), where the file denotes the file that needs to be read. Files can also be read using the Streamreader as bytes. This article will cover in detail the various methods that are available in C# for reading a file along with appropriate examples.

Syntax:

The ReadAllText() has the following syntax

public static string ReadAllText (String Path, System.Text.Encoding encoding)
Copy after login

The ReadAllLines() has the following syntax

public static string ReadAllLines(String, Encoding)
Copy after login

This method reads all the lines that are present in the file and then stores them in a string and then closes the file.

Parameters of C# Read File

  • Path: The path contains the location of the files. This file must be read.
  • Encoding: This denotes the encoding type of the file, this is optional.

The return type of this method is a string that has all the contents in the file. This method is available in the System.IO namespace and the assembly that is associated with this method is mscorlib.dll.

Exceptions associated with ReadAllText() of ReadAllLines() method:

  • Argument Exception: This occurs when the path has zero characters, white spaces, or invalid characters.
  • Argument Null Exception: This occurs when the path is null.
  • Path Too Long Exception: This occurs when the path exceeds the actual system defined limit.
  • IO Exception: When opening the file if any error occurs, this exception occurs.
  • UnAuthorized Access Exception: This occurs when the specified file is read only
  • File Not Found Exception: This occurs when the file is not there in the specified location.
  • Not Supported Exception: When the specified path is in invalid format, this exception is thrown.
  • Security Exception: When the user doesn’t have access to the file, this exception is thrown.

Examples of C# Read File

Here are the following examples mentioned below.

Example#1 – Reading a file using ReadAllText()

Code:

using System;
using System.IO;
using System.Text;
namespace ReadAllText
{
class Test
{
static void Main(string[] args)
{
var Fpath= @"C:\Vignesh\KB.txt";
string content = File.ReadAllText(Fpath, Encoding.UTF8);
Console.WriteLine(content);
}
}
}
Copy after login

Output:

C# Read File

Example #2 – Reading a file using ReadAllLines()

Code:

using System;
using System.IO;
using System.Text;
namespace ReadAllLines
{
class Test
{
static void Main(string[] args)
{
var inputfile = @"C:\Vignesh\append.txt";
string[] output = File.ReadAllLines(inputfile, Encoding.UTF8);
foreach (string op in output)
{
Console.WriteLine(op);
}
}
}
}
Copy after login

Output:

C# Read File

Example #3 – Reading a file using streamreader class

1. StreamReader.ReadToEnd(): This method is used to read the file from the current position to the end of the stream. The corresponding namespace for this method is System.Io and assembly is mscorblib.dll.

Syntax:

public override string ReadToEnd ();
Copy after login

Input Parameters: This method doesn’t require any input parameter.

Returns: This method outputs the file content as stream, if the current position is set to last character of the file an empty string is returned.

2. StreamReader.ReadLine(): This method reads the characters from the current stream and sends the data as a string to the output. The corresponding namespace for this method is System.Io and assembly is mscorblib.dll.

Syntax:

public override string ReadLine();
Copy after login

Input Parameters: This method doesn’t require any input parameter.

Returns: It returns the next line to the current stream, if the current stream is in the last line position then null is returned.

Code:

using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
var FP = @"C:\Vignesh\Names.txt";
using var fstre = new FileStream(FP, FileMode.Open, FileAccess.Read);
using var sree = new StreamReader(fstre, Encoding.UTF8);
string Fcontent = sree.ReadToEnd();
Console.WriteLine(Fcontent);
}
}
Copy after login

Output:

C# Read File

Code:

using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
var filpath = @"C:\Vignesh\TimerJob-2019-08-09.txt";
using var fstre = new FileStream(filpath, FileMode.Open, FileAccess.Read);
using var sreee = new StreamReader(fstre, Encoding.UTF8);
string cline = String.Empty;
while ((cline = sreee.ReadLine()) != null)
{
Console.WriteLine(cline);
}
}
}
Copy after login

Output:

C# Read File

Code:

using System;
using System.IO;
namespace testclass {
class Test {
string FPath = @ "C:\Vignesh\Script to 0365 connection.txt";
static void Main(string[] args)
{
//Check if file is there at the path
//ReadallOutput()
if (File.Exists(FPath)) {
string output = File.ReadAlloutput(FPath);
Console.WriteLine(output);
}
//Check if file is there at the path
if (File.Exists(FPath)) {
//ReadallLines()
string[] Flines = File.ReadAllFlines(FPath);
foreach(string line in Flines)
Console.WriteLine(line);
}
//Check if file is there at the path
if (File.Exists(FPath)) {
//using streamreader
using(StreamReader file = new StreamReader(FPath)) {
int counter = 0;
string lgth;
while ((lgth = file.ReadLine()) != null) {
Console.WriteLine(lgth);
counter++;
}
file.Close();
}
}
Console.ReadKey();
}
}
}
Copy after login

Output:

C# Read File

Example #4 – Reading a file asynchronously using streamreader

Code:

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
class TestProgram
{
static async Task Main(string[] args)
{
var ip = @" C:\Vignesh\Patching\Patching Steps.txt";
using var fssss = new FileStream(ip, FileMode.Open, FileAccess.Read);
using var srrr = new StreamReader(fssss, Encoding.UTF8);
//Reading asynchronously
string op = await srrr.ReadToEndAsync();
Console.WriteLine(op);
}
}
Copy after login

Output:

C# Read File

Conclusion

Thus, the article covered in detail the read file functionality in c#. It explained the various methods that are available to perform the operation. It also covered various parameters and exceptions that are associated with each method and explained in detail along with the example of sample programs. To cover more in detail, it is advisable to write sample programs and practice them.

The above is the detailed content of C# Read File. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!