Menu

Code-Bytes

Byte-sized articles, to get things done

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!

2
174
3/22/2025

Working with dates is a common requirement in many applications, and calculating the difference between two dates is a particularly frequent task.

C# provides several powerful built-in methods to handle date arithmetic efficiently. Let's explore how to calculate date differences in C#.

Using DateTime and TimeSpan

The most straightforward way to calculate the difference between two dates in C# is by using the DateTime struct and the TimeSpan class:

DateTime startDate = new DateTime(2023, 1, 1);
DateTime endDate = new DateTime(2023, 12, 31);

TimeSpan difference = endDate - startDate;

Console.WriteLine($"Total days: {difference.TotalDays}");
Console.WriteLine($"Total hours: {difference.TotalHours}");
Console.WriteLine($"Total minutes: {difference.TotalMinutes}");
Console.WriteLine($"Total seconds: {difference.TotalSeconds}");

Getting Specific Units

Sometimes you need the difference in specific units (years, months, days). The TimeSpan class doesn't directly provide years and months, since these units vary in length. Here's how to handle this:

int years = endDate.Year - startDate.Year;
int months = endDate.Month - startDate.Month;

if (months < 0)
{
    years--;
    months += 12;
}

// Adjust for day differences
if (endDate.Day < startDate.Day)
{
    months--;
    int daysInMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month);
    int dayDifference = daysInMonth - startDate.Day + endDate.Day;
    Console.WriteLine($"Years: {years}, Months: {months}, Days: {dayDifference}");
}
else
{
    int dayDifference = endDate.Day - startDate.Day;
    Console.WriteLine($"Years: {years}, Months: {months}, Days: {dayDifference}");
}

Using DateTimeOffset for Time Zone Awareness

If your application needs to handle dates across different time zones, consider using DateTimeOffset:

DateTimeOffset startDateOffset = new DateTimeOffset(2023, 1, 1, 0, 0, 0, TimeSpan.FromHours(-5));
DateTimeOffset endDateOffset = new DateTimeOffset(2023, 12, 31, 0, 0, 0, TimeSpan.FromHours(1));

TimeSpan timeDifference = endDateOffset - startDateOffset;
Console.WriteLine($"Total days including time zone difference: {timeDifference.TotalDays}");

Practical Applications

Date difference calculations are useful in many scenarios:

  • Calculating age from birth date
  • Determining duration between events
  • Computing business days between dates
  • Scheduling recurring events

With these techniques, you can handle most date arithmetic requirements in your C# applications efficiently and accurately.

0
110
3/22/2025

Storing passwords as plain text is dangerous. Instead, you should hash them using a strong, slow hashing algorithm like BCrypt, which includes built-in salting and resistance to brute-force attacks.

Step 1: Install BCrypt NuGet Package

Before using BCrypt, install the BCrypt.Net-Next package:

dotnet add package BCrypt.Net-Next

or via NuGet Package Manager:

Install-Package BCrypt.Net-Next

Step 2: Hash a Password

Use BCrypt.HashPassword() to securely hash a password before storing it:

using BCrypt.Net;

string password = "mySecurePassword123";
string hashedPassword = BCrypt.HashPassword(password);

Console.WriteLine(hashedPassword); // Output: $2a$12$...

Step 3: Verify a Password

To check a user's login attempt, use BCrypt.Verify():

bool isMatch = BCrypt.Verify("mySecurePassword123", hashedPassword);
Console.WriteLine(isMatch); // Output: True

Ensuring proper hashing should be at the top of your list when it comes to building authentication systems.

0
174
3/22/2025

Measuring the execution time of C# methods is essential for performance optimization and identifying bottlenecks in your application.

The most straightforward approach uses the Stopwatch class from the System.Diagnostics namespace, which provides high-precision timing capabilities.

This approach is perfect for quick performance checks during development or when troubleshooting specific methods in production code.

Here's a practical example: Imagine you have a method that processes a large dataset and you want to measure its performance.

First, add using System.Diagnostics; to your imports. Then implement timing as shown below:

public void MeasurePerformance()
{
    Stopwatch stopwatch = new Stopwatch();
    
    // Start timing
    stopwatch.Start();
    
    // Call the method you want to measure
    ProcessLargeDataset();
    
    // Stop timing
    stopwatch.Stop();
    
    // Get the elapsed time
    Console.WriteLine($"Processing time: {stopwatch.ElapsedMilliseconds} ms");
    // Or use ElapsedTicks for higher precision
    Console.WriteLine($"Processing ticks: {stopwatch.ElapsedTicks}");
}

For more advanced scenarios, consider using the BenchmarkDotNet library, which offers comprehensive benchmarking with statistical analysis.

Simply install the NuGet package, decorate methods with the [Benchmark] attribute, and run BenchmarkRunner.Run<YourBenchmarkClass>() to generate detailed reports comparing different implementation strategies.

0
97
3/22/2025

Closing a SqlDataReader correctly prevents memory leaks, connection issues, and unclosed resources. Here’s the best way to do it.

Use 'using' to Auto-Close

Using using statements ensures SqlDataReader and SqlConnection are closed even if an exception occurs.

Example

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn))
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine(reader["Username"]);
        }
    } // ✅ Auto-closes reader here
} // ✅ Auto-closes connection here

This approach auto-closes resources when done and it is cleaner and less error-prone than manual closing.

⚡ Alternative: Manually Close in finally Block

If you need explicit control, you can manually close it inside a finally block.

SqlDataReader? reader = null;
try
{
    using SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();
    using SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn);
    reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        Console.WriteLine(reader["Username"]);
    }
}
finally
{
    reader?.Close();  // ✅ Closes reader if it was opened
}

This is slightly more error prone if you forget to add a finally block. But might make sense when you need to handle the reader separately from the command or connection.

0
71
3/22/2025

Duplicate records in SQL Server can lead to inaccurate reporting, data inconsistencies, and performance issues. In this article, we’ll go over how to identify and safely remove duplicate rows while keeping at least one unique record.

Detecting Duplicates

To find duplicate records in a table, use the GROUP BY and HAVING clauses to count occurrences of each unique combination of values:

SELECT column1, column2, COUNT(*)
FROM YourTable
GROUP BY column1, column2
HAVING COUNT(*) > 1;

Replace column1, column2 with the columns that define a duplicate in your dataset.

If you need to see the actual duplicate rows, use a ROW_NUMBER() approach:

SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY column1, column2 ORDER BY id) AS row_num
    FROM YourTable
) t
WHERE row_num > 1;

Here, id should be a unique column to order the duplicates.

Removing Duplicates

Method 1: Using ROW_NUMBER()

The safest way to remove duplicates while keeping one unique record is by using ROW_NUMBER().

WITH CTE AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY column1, column2 ORDER BY id) AS row_num
    FROM YourTable
)
DELETE FROM CTE WHERE row_num > 1;

This deletes all duplicate records while keeping the first occurrence.

Method 2: Using DISTINCT INTO a New Table

If you want to be extra cautious, create a new table with only unique records:

SELECT DISTINCT * INTO NewTable FROM YourTable;

Then, drop the old table and rename NewTable back to YourTable.

Final Thoughts

Always backup your data before running delete operations to prevent accidental data loss. By regularly cleaning up duplicates, you can keep your SQL Server database efficient and reliable.

0
16
3/22/2025

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.

Writing XML Using XmlWriter

XmlWriter provides a fast and memory-efficient way to generate XML files by writing elements sequentially.

Example:

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):

<?xml version="1.0" encoding="utf-8"?>
<Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <Age>30</Age>
</Person>

Writing XML Using XDocument

The XDocument class from LINQ to XML provides a more readable and flexible way to create XML files.

Example:

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.

When to Use Each Method

  • Use XmlWriter when performance is critical and you need to write XML sequentially.
  • Use XDocument when you need a more readable, maintainable, and flexible way to manipulate XML.

Conclusion

Writing XML files in C# is straightforward with XmlWriter and XDocument. Choose the method that best suits your needs for performance, readability, and maintainability.

0
46
3/22/2025

File-scoped namespaces, introduced in C# 10, provide a more concise way to declare namespaces in your code files.

This feature helps reduce nesting levels and makes your code cleaner and more readable. Let's explore how to use them effectively and understand their benefits.

Traditional Namespace Declaration

Traditionally, C# developers have used block-scoped namespaces, which require curly braces and add an extra level of indentation:

namespace MyCompany.MyProduct.Features
{
    public class UserService
    {
        private readonly string _connectionString;

        public UserService(string connectionString)
        {
            _connectionString = connectionString;
        }

        public void CreateUser(string username)
        {
            // Implementation
        }
    }

    public record User(string Username, string Email);
}

Modern File-Scoped Namespace

With file-scoped namespaces, you can declare the namespace without braces, reducing indentation and making the code more readable:

namespace MyCompany.MyProduct.Features;

public class UserService
{
    private readonly string _connectionString;

    public UserService(string connectionString)
    {
        _connectionString = connectionString;
    }

    public void CreateUser(string username)
    {
        // Implementation
    }
}

public record User(string Username, string Email);

Key Benefits and Best Practices

  1. Reduced Indentation: File-scoped namespaces eliminate one level of indentation, making the code easier to read and maintain.

  2. Single Namespace per File: File-scoped namespaces enforce a good practice of having only one namespace per file, improving code organization.

  3. Compatibility: File-scoped namespaces work seamlessly with existing code and can be gradually adopted in your codebase.

Important Considerations

When using file-scoped namespaces, keep these points in mind:

  • You can only have one namespace declaration per file
  • The namespace declaration must be the first non-comment line in the file
  • You cannot mix traditional and file-scoped namespace declarations in the same file

Migration Tips

When converting existing code to use file-scoped namespaces:

  1. Start with new files, using file-scoped namespaces from the beginning
  2. Gradually convert existing files during regular maintenance work
  3. Use IDE tools to automate the conversion process
  4. Ensure your team agrees on the migration approach and timeline

Conclusion

File-scoped namespaces are a simple yet effective feature that can make your C# code more readable and maintainable. While the benefits might seem small, they add up significantly in larger codebases. Consider adopting this modern syntax in your C# projects, especially if you're using C# 10 or later.

0
87
3/22/2025

Raw string literals in C# provide a flexible way to work with multiline strings, with some interesting rules around how quotes work.

The key insight is that you can use any number of double quotes (three or more) to delimit your string, as long as the opening and closing sequences have the same number of quotes.

The Basic Rules

  1. You must use at least three double quotes (""") to start and end a raw string literal
  2. The opening and closing quotes must have the same count
  3. The closing quotes must be on their own line for proper indentation
  4. If your string content contains a sequence of double quotes, you need to use more quotes in your delimiter than the longest sequence in your content

Examples with Different Quote Counts

// Three quotes - most common usage
string basic = """
    This is a basic
    multiline string
    """;

// Four quotes - when your content has three quotes
string withThreeQuotes = """"
    Here's some text with """quoted""" content
    """";

// Five quotes - when your content has four quotes
string withFourQuotes = """""
    Here's text with """"nested"""" quotes
    """"";

// Six quotes - for even more complex scenarios
string withFiveQuotes = """"""
    Look at these """""nested""""" quotes!
    """""";

The N+1 Rule

The general rule is that if your string content contains N consecutive double quotes, you need to wrap the entire string with at least N+1 quotes. This ensures the compiler can properly distinguish between your content and the string's delimiters.

// Example demonstrating the N+1 rule
string example1 = """
    No quotes inside
    """; // 3 quotes is fine

string example2 = """"
    Contains """three quotes"""
    """"; // Needs 4 quotes (3+1)

string example3 = """""
    Has """"four quotes""""
    """""; // Needs 5 quotes (4+1)

Practical Tips

  • Start with three quotes (""") as your default
  • Only increase the quote count when you actually need to embed quote sequences in your content
  • The closing quotes must be on their own line and should line up with the indentation you want
  • Any whitespace to the left of the closing quotes defines the baseline indentation
// Indentation example
string properlyIndented = """
    {
        "property": "value",
        "nested": {
            "deeper": "content"
        }
    }
    """; // This line's position determines the indentation

This flexibility with quote counts makes raw string literals extremely versatile, especially when dealing with content that itself contains quotes, like JSON, XML, or other structured text formats.

0
68
3/22/2025

When working with large files, reading the entire file at once may be inefficient or unnecessary, especially when you only need the first few lines.

In C#, you can easily read just the first N lines of a file, improving performance and resource management.

Why Read Only the First N Lines?

Reading only the first few lines of a file can be beneficial for:

  • Quickly checking file contents or formats.
  • Processing large files without consuming excessive memory.
  • Displaying previews or samples of file content.

Reading the First N Lines with StreamReader

Here's a simple and efficient method using C#:

using System;
using System.IO;

class FileReader
{
    /// <summary>
    /// Reads the first N lines from a file.
    /// </summary>
    /// <param name="filePath">The path to the file.</param>
    /// <param name="numberOfLines">Number of lines to read.</param>
    /// <returns>Array of strings containing the lines read.</returns>
    public static string[] ReadFirstNLines(string filePath, int numberOfLines)
    {
        List<string> lines = new List<string>();

        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            int counter = 0;

            // Read lines until the counter reaches numberOfLines or EOF
            while (counter < numberOfLines && (line = reader.ReadLine()) != null)
            {
                lines.Add(line);
                counter++;
            }
        }

        return lines.ToArray();
    }

Example Usage

Here's a practical example demonstrating the usage of the method above:

string filePath = "C:\\largefile.txt";
int linesToRead = 10;

string[] firstLines = FileReader.ReadFirstNLines(filePath, firstLinesCount);

foreach (string line in firstLines)
{
    Console.WriteLine(line);
}

Efficient and Shorter Alternative with LINQ

For a concise implementation, LINQ can also be used:

using System;
using System.IO;
using System.Linq;

class FileReader
{
    public static IEnumerable<string> ReadFirstNLines(string filePath, int numberOfLines)
    {
        // Take first N lines directly using LINQ
        return File.ReadLines(filePath).Take(numberOfLines);
    }
}

Usage Example with LINQ Method:

string path = "C:\\largeFile.txt";
int n = 10;

var lines = FileReader.ReadFirstNLines(path, n);

foreach (string line in lines)
{
    Console.WriteLine(line);
}

Best Practices

  • Use File.ReadLines instead of File.ReadAllLines for large files, as it does not load the entire file into memory.
  • Always handle exceptions properly to ensure your application remains stable.
  • For large files, avoid methods like ReadAllLines() which can negatively affect performance.

Final Thoughts

By limiting your reading operations to only the first few lines you actually need, you significantly enhance your application's efficiency and resource management.

0
36
3/22/2025