How to Read from and Write to Text Files in C#

How to Read from and Write to Text Files in C#



It is one of the common operations that you will be doing while doing C# programming when you are developing a console, desktop application, or website. In this blog post, I'll cover a sample implementation on how to read from and write to a text file in C# with examples.

1. Why Work with Text Files?



Text files are lightweight and platform-independent. They are best suited for storing configuration data, logs, and other types of information that do not require complex databases.


2. Reading from Text Files


There are several ways to read text files in C# such as File.ReadAllText(), File.ReadAllLines(), and StreamReader.


Example 1: Reading the whole file as a string


using System;

using System.IO;


class Program

{

static void Main()

{

string filePath = "example.txt";

// if File exists

if (File.Exists(filePath))

{

string content = File.ReadAllText(filePath);

Console.WriteLine("File Content:

" + content);

}

else

Console.WriteLine("File not found!");

}

}


Example 2: Read File Line by Line


using System;

using System.IO;


class Program

static void Main()

{

string filePath = "example.txt";


if (File.Exists(filePath))

{

string[] lines = File.ReadAllLines(filePath);

foreach (string line in lines)

{

Console.WriteLine(line);

}

}

}


}


3. Writing to Text Files


C# has methods such as File.WriteAllText(), File.WriteAllLines(), and StreamWriter for writing to files.


Example 1: Write Text to a File


using System;

using System.IO;


class Program

{

static void Main()

{

string filePath = "output.txt";

string content = "Hello, C#! This is a sample text.";

File.WriteAllText(filePath, content);

Console.WriteLine("File written successfully!");

End

Example 2: Append Text to a File

using System;

using System.IO;


class Program

static void Main()

string filePath = "output.txt";

string content = "This line is appended.";

File.AppendAllText(filePath, content + Environment.NewLine);

Console.WriteLine("Text appended successfully!");

}

End

4. Using StreamReader and StreamWriter


StreamReader and StreamWriter are utilized to read and write files wherein the file too big or when reading or writing lines.

Reading with StreamReader


using System;

using System.IO;



Class Program

static void Main()

{

string filePath = "example.txt";

;

using (StreamReader reader = new StreamReader(filePath))

{

string line;

while ((line = reader.ReadLine())!= null)

Console.WriteLine(line);

}

}

}

string filePath = "output.txt";


using (StreamWriter writer = new StreamWriter(filePath, true))

{

writer.WriteLine("This is a new line added using StreamWriter.");

}


Console.WriteLine("File written successfully!");

}

}


5. Best Practices


1. Check for File Existence: File.Exists() is used to avoid exceptions.




2. Use of using Statement: Automatically closes the files after reading/writing.




3. Error Handling: Use try-catch blocks to handle file-related errors.




4. Path Management: Use Path. Combine() for crossplatform file paths.


---------------------------------------------------


Conclusion



Reading and writing text files in C# is extremely easy when using classes from System.IO namespace. From rather simple file access to somewhat more complex file handling by streams, choose what fits your applications needs. Happy coding!

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.