String manipulation in C#

- Posted in Coding by

Here is a method that, if passed a proper noun, such as a person's name or a street address, will return a properly formatted version of that string:

And here is an example of using method ProperlyCapitalizeName in a program:

Bytes to characters and vice versa

- Posted in Coding by

It just so happens that any character we might use in a string has a numerical encoding. The alphabet ranges from 65-90 for capital letters A through Z, and from 97-122 for lowercase letters a-z. When we want to work with text encoding, we need to add the following namespace to the top of our source code file:

using System.Text;

The numerical representation of our English alphabet takes the form of unique numbers for each upper and lowercase letter, and these are stored in a variable type called byte. A byte is an 8-bit integer that can hold values from 0 to 255.

If we have a string variable named sChar, we can obtain its numerical encoding as follows, if we have referenced the System.Text namespace:

byte[] bt = Encoding.Default.GetBytes(sChar);

The reverse is encoding bytes to characters. If we have an array of bytes, we can convert each element’s value to its corresponding character:

byte[] bytes = {40, 80, 20};
char result;
foreach(byte number in bytes)
{
  result = Convert.ToChar(number);
  Console.WriteLine(“{0} converts to {1}.”, number, result);
}

Full source code listing:

download sourcecode

Recursive file counting

- Posted in Coding by
using System;
using System.Reflection;
using System.IO;

namespace GetFilesRecursively {
class Program {

    static void Main(){
        int cnt = 0;
        long bites = 0;
        string p = string.Empty;
        foreach (string file in System.IO.Directory.GetFiles(
            GetExecutingDirectoryName(), "*",SearchOption.AllDirectories))
        {
            cnt++;
            FileInfo fi = new FileInfo(file);
            bites += fi.Length;
            //do something with file
            p = String.Format("{0:n0}", (int)bites);
        }   
        Console.Write(" Total files: {0}, ", cnt.ToString());
        Console.WriteLine("totaling {0} bytes.", p);
    }

    /* found following method here: 
    https://www.red-gate.com/simple-talk/blogs/c-getting-
    the-directory-of-a-running-executable/ */
    public static string GetExecutingDirectoryName()
    {
        var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
        return new FileInfo(location.AbsolutePath).Directory.FullName;
    }       
  }
}