Schlagwort: System Tools

Strip BOM from a File or Text

The following code removes the BOM (Byte Order Mark) from texts. Some text editors add that while saving files. Sometimes this leads to problems while reading or converting text files (e.g. XML files). The code removes the BOM and Zero White Spaces from the string and returns the clean string. /// <summary> /// Strips the…

Get the Path of the Executing Assembly

public static string GetExecutingAssemblyPath() { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); }  

Using a Comparer to Sort CultureInfos by their Name

If you need to show a list of languages, or more general CultureInfos, you might want to sort them by the name they show up in the GUI. This can easily be done by using a custom comparer. This implements the generic IComparer<T> interface. public class CultureInfoComparer : IComparer<CultureInfo> { public int Compare(CultureInfo x, CultureInfo…

Calendar tools and algorithms

Calculating a leap year The correct calculation of a leap year was first introduced by pope Gregor in 1582. The Gregorian Calendar is still commonly used in most parts of the world. Before that, the leap years were simply defined being every 4th year. public static bool IsLeapYear(int year) { if (year % 100 ==…

Change string into a valid file name

Not all possible characters are suitable for file names. For example path separators cannot be used for file names. This changes any string into a valid file name by replacing the invalid characters with an underscore: public static string GetValidFileName(string fileName) { foreach (char c in Path.GetInvalidFileNameChars()) {   fileName = fileName.Replace(c, ‚_‘); } return fileName; }  

Check if current user has admin rights and restart application with elevated rights

The following code snippet checks if the current user as administrator rights: /// <summary> /// Checks if user has administrator rights /// </summary> public static bool UserIsAdmin() {   WindowsIdentity identity = WindowsIdentity.GetCurrent();   WindowsPrincipal principal = new WindowsPrincipal(identity);   return principal.IsInRole(WindowsBuiltInRole.Administrator); } If the application requires administrator rights for an operation, the following function can be used to restart the application with elevated rights: /// <summary> /// Restarts the current application with admin rights. /// </summary>…