C# Snippets

Fastest way to remote all whitespace from a string:

Regex.Replace(someString, @"\s+", "")

Generate Random Numbers

private static int GenerateRandomNumber()
        {
            var random = new Random((int)DateTime.Now.Ticks);
            return random.Next(18000, 35000);
        }

Current Project Directory

string startupPath = System.IO.Directory.GetCurrentDirectory();

or

string startupPath = Environment.CurrentDirectory;

Generate New GUID

Guid.NewGuid()

Convert epoch time

public static class TimeConversionHelper{
        public static DateTime FromUnixTime(long unixTimeInMilliseconds){
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return epoch.AddMilliseconds(unixTimeInMilliseconds);
        }
    }

Get file extension and determin if it's an image

public static class FileExtensionHelper{
        private static string GetFileExtension(string fileName){
            var locationOfLastDot = fileName.LastIndexOf('.');
            return locationOfLastDot > 0 ? fileName.Substring(locationOfLastDot + 1) : String.Empty;
        }

        public static bool IsFileAnImage(string fileName){
            var fileExtension = GetFileExtension(fileName);
            switch (fileExtension){
                case "jpg" :
                    return true;
                default:
                    return false;
            }
        }
    }

Use Reflection to get the primitive type

Type t = typeof(string);
string typeName;
using (var provider = new CSharpCodeProvider()){
var typeRef = new CodeTypeReference(t);
typeName = provider.GetTypeOutput(typeRef);
}

Save and Load a Memory Stream To/From a File

memoryStream.WriteTo(fileStream);

or in .net 4.5, then:

fileStream.CopyTo(memoryStream);
memoryStream.CopyTo(fileStream);