Here are just a few of the "helpers" I frequently include in web applications to make life easier.
StringListFromDelimitedString
public static List<string> StringListFromDelimitedString(string commaDelimitedString, string delimiter = ",")
{
List<string> rtnVal = new List<string>();
if (commaDelimitedString != null)
{
rtnVal = commaDelimitedString.Split(new[] { delimiter },
StringSplitOptions.RemoveEmptyEntries).Select(b => b.Trim()).ToList();
}
return rtnVal;
}
IntListFromCommaDelimitedString
public static List<int> IntListFromCommaDelimitedString(string commaDelimitedString)
{
List<int> rtnVal = new List<int>();
if (!string.IsNullOrWhiteSpace(commaDelimitedString))
{
List<string> stringList = StringListFromCommaDelimitedString(commaDelimitedString);
foreach (var value in stringList)
{
int intValue = 0;
bool parse = int.TryParse(value, out intValue);
if (parse)
{
rtnVal.Add(intValue);
}
}
}
return rtnVal;
}
CommaDelimitedStringFromStringList
public static string CommaDelimitedStringFromStringList(List<string> stringList, bool spaceAfterComma = false)
{
string rtnVal = "";
string delimiter = !spaceAfterComma ? "," : ", ";
stringList.RemoveAll(o => String.IsNullOrWhiteSpace(o));
rtnVal = string.Join(delimiter, stringList);
return rtnVal;
}
StringFromQueryString
public static string stringFromQueryString(string queryString, string defaultValue = "")
{
string rtrnVal = defaultValue;
HttpRequest request = HttpContext.Current.Request;
if (request.QueryString[queryString] != null)
{
string queryStringValue = request.QueryString[queryString];
rtrnVal = queryStringValue;
}
return rtrnVal;
}
GetRootPath
public static string GetRootPath()
{
return HttpContext.Current.Server.MapPath("~");
}
FileExists
public static bool FileExists(string fileName)
{
// note: all paths should start with a character and end with a "/"
bool rtnVal = false;
string rootPath = HttpContext.Current.Server.MapPath("~");
string fileSpec = string.Format("{0}{1}", rootPath, fileName);
if (File.Exists(fileSpec))
{
rtnVal = true;
}
return rtnVal;
}