Pages

Showing posts with label Text. Show all posts
Showing posts with label Text. Show all posts

Thursday, April 26, 2012

C# Left, Mid and Right functions

To simulate the VB functions Left, Mid and Right, you could implement string extension methods in C#, like this:

Left

public static string Left(this string value, int length)
{
    if (string.IsNullOrEmpty(value))
    {
        return value;
    }

    return value.Substring(0, length);
}    

Mid

public static string Mid(this string value, int startPosition, int endPosition)
{
    if (string.IsNullOrEmpty(value))
    {
        return value;
    } 

    return value.Substring(startPosition, endPosition);
}  

Right

public static string Right(this string value, int length)
{
    if (string.IsNullOrEmpty(value))
    {
        return value;
    }         

    return value.Substring(value.Length - length);            
}


Then you could use them like this:

someString.Left(5);

someString.Mid(5, 20);

someString.Right(9);

Note that I'm not really sanitizing any exceptions that may occur, like, for example, if the string passed in is smaller than the one we try to get. You should implement that defensive code yourself. :)

Thursday, March 29, 2012

LINQ to Text Files

LINQing it

If you ever need to find something specific inside a text file, I'd advise you to go with LINQ.
Below is a very useful extension method to work with Text Files' content with LINQ:

static class Extensions
{
    public static IEnumerable<string> Lines(this StreamReader reader)
    {
        string line;
        
        while (!string.IsNullOrEmpty(line = reader.ReadLine()))
        {
            yield return line;
        }
    }
}

So with the above extension method in context, you could simply do things like this:


using (var sr = new StreamReader(myPath))
{
    var results = from line in sr.Lines()
                  where line.StartsWith("Foo") && line.Contains("this text")
                  select line;
}

This makes life a little easier.