Monday, May 7, 2012

C# Escaping Generic Objects for SQL Server

In response to a need to escape various fields within any given class object, I worked up this guy. Essentially, iterates through all members of a given object and replaces single quotes with doubles on any String object. private static void SQLServerEscapeObject(object obj) { foreach (System.Reflection.PropertyInfo property in obj.GetType().GetProperties()) { try { if (property.PropertyType.FullName == "System.String" && property.GetValue(obj, null) != null) { property.SetValue(obj, property.GetValue(obj, null).ToString().Replace("'", "''"), null); } } catch (Exception e) { Logger.Log("Issue clensing SQL query: " + e.Message, Logger.Loglevel.Warning); } } return; }