Schlagwort: C#

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…

Check if Code is Executed at Design Time

Sometimes it is important to prevent certain code being executed at design time. public static bool IsDesignTime { get { return (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime); } } In WPF applications the following code can be used instead: public static bool IsDesignTime { get { System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()); } }  

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 ==…

Check Availability of a Server

This checks the availability of a server by sending a ping to the given IP address and waiting a certain amount of time for a response from the server: public static bool ServerAvailable(string ip, int timeout) { Ping pingSender = new Ping(); PingReply reply; try { reply = pingSender.Send(ip, timeout); } catch { return false;…

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; }  

Convert Image to Byte Array (and back)

The following functions can be used to convert an image object to a byte array (and vise versa). This is often used to store images in a database or file or to use them in a stream. /// <summary> /// Converts an image to a byte array. /// </summary> /// <param name=“image“>The image.</param> /// <returns>Byte…

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>…

Change Image into an Icon

The following C# code changes an image object into an icon. public static Icon ConvertImageToIcon(Image img) { if (img == null) return null; Bitmap square = new Bitmap(img.Width, img.Height); // create new bitmap Graphics g = Graphics.FromImage(square); // allow drawing to it g.DrawImage(img, 0, 0, img.Width, img.Height); // draw image with specified dimensions g.Flush(); //…