Reading a file line by line is useful when handling large files without loading everything into memory at once.
✅ Best Practice: Use File.ReadLines() which is more memory efficient.
Example
foreach (string line in File.ReadLines("file.txt")) { Console.WriteLine(line); }
Why use ReadLines()?
Reads one line at a time, reducing overall memory usage. Ideal for large files (e.g., logs, CSVs).
Alternative: Use StreamReader (More Control)
For scenarios where you need custom processing while reading the contents of the file:
using (StreamReader reader = new StreamReader("file.txt")) { string? line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } }
Why use StreamReader?
Lets you handle exceptions, encoding, and buffering. Supports custom processing (e.g., search for a keyword while reading).
When to Use ReadAllLines()? If you need all lines at once, use:
string[] lines = File.ReadAllLines("file.txt");
Caution: Loads the entire file into memory—avoid for large files!
Using SqlDataReader asynchronously prevents blocking the main thread, improving performance in web apps and large queries. Here’s how to do it properly.
Use await with ExecuteReaderAsync()
using (SqlConnection conn = new SqlConnection(connectionString)) { await conn.OpenAsync(); using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn)) using (SqlDataReader reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { Console.WriteLine(reader["Username"]); } } // ✅ Auto-closes reader } // ✅ Auto-closes connection
Why use async?
A couple of reasons:
⚡ Alternative: ConfigureAwait(false) for ASP.NET
Use ConfigureAwait(false) in library code to avoid deadlocks in UI frameworks like ASP.NET.
using (SqlConnection conn = new SqlConnection(connectionString)) { await conn.OpenAsync().ConfigureAwait(false); using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn)) using (SqlDataReader reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) { while (await reader.ReadAsync().ConfigureAwait(false)) { Console.WriteLine(reader["Username"]); } } }
When working with URLs in C#, encoding is essential to ensure that special characters (like spaces, ?, &, and =) don’t break the URL structure. The recommended way to encode a string for a URL is by using Uri.EscapeDataString(), which converts unsafe characters into their percent-encoded equivalents.
string rawText = "hello world!"; string encodedText = Uri.EscapeDataString(rawText); Console.WriteLine(encodedText); // Output: hello%20world%21
This method encodes spaces as %20, making it ideal for query parameters.
For ASP.NET applications, you can also use HttpUtility.UrlEncode() (from System.Web), which encodes spaces as +:
using System.Web; string encodedText = HttpUtility.UrlEncode("hello world!"); Console.WriteLine(encodedText); // Output: hello+world%21
For .NET Core and later, Uri.EscapeDataString() is the preferred choice.
XML (Extensible Markup Language) is a widely used format for storing and transporting data.
In C#, you can create XML files efficiently using the XmlWriter and XDocument classes. This guide covers both methods with practical examples.
XmlWriter
XDocument
XmlWriter provides a fast and memory-efficient way to generate XML files by writing elements sequentially.
using System; using System.Xml; class Program { static void Main() { using (XmlWriter writer = XmlWriter.Create("person.xml")) { writer.WriteStartDocument(); writer.WriteStartElement("Person"); writer.WriteElementString("FirstName", "John"); writer.WriteElementString("LastName", "Doe"); writer.WriteElementString("Age", "30"); writer.WriteEndElement(); writer.WriteEndDocument(); } Console.WriteLine("XML file created successfully."); } }
Output (person.xml):
person.xml
<?xml version="1.0" encoding="utf-8"?> <Person> <FirstName>John</FirstName> <LastName>Doe</LastName> <Age>30</Age> </Person>
The XDocument class from LINQ to XML provides a more readable and flexible way to create XML files.
using System; using System.Xml.Linq; class Program { static void Main() { XDocument doc = new XDocument( new XElement("Person", new XElement("FirstName", "John"), new XElement("LastName", "Doe"), new XElement("Age", "30") ) ); doc.Save("person.xml"); Console.WriteLine("XML file created successfully."); } }
This approach is ideal for working with complex XML structures and integrating LINQ queries.
Writing XML files in C# is straightforward with XmlWriter and XDocument. Choose the method that best suits your needs for performance, readability, and maintainability.
Register for my free weekly newsletter.