.Net Strings
String.Format(?)
For use with obj.ToString("x") and string.Format("The value is {0:x)",obj) (msdn)
CultureInfo c = new CultureInfo("en-CA");
decimal dec = 19.956m;
Assert.AreEqual("$19.96", dec.ToString("C", c)); //currency
Assert.AreEqual("19.96", dec.ToString("F2", c)); //decimal places (rounding)
Assert.AreEqual("019", 19.ToString("D3", c)); //integers- add leading zeroes
//Dates
DateTime d = new DateTime(2009, 5, 10, 13, 25, 10);
Assert.AreEqual("10/05/2009", d.ToString("d", c)); //short date
Assert.AreEqual("2009/05/10 13:25:10",
d.ToString("yyyy/MM/dd HH:mm:ss", c)); //specific format
Assert.AreEqual("2009-05-10T13:25:10",
d.ToString("s", c)); //sortable
//MM is month, mm is minute, HH is 24hour, hh is 12hour
//Alignment comma with padding (- for left align)
Assert.AreEqual("City: Ft Meade Zip: 21113",
String.Format("City: {0,-20} Zip: {1,10}", "Ft Meade", "21113"));
//Conditional
Assert.AreEqual("positive",
String.Format("{0:positive;negative;zero}", 10)); //"positive" for >0 etc
Enums
- string s = enumValue.ToString();
- MyEnum value = (MyEnum)Enum.Parse(typeof(MyEnum), key, true);
- Throws ArgumentException if not in enum. There's no TryParse.
- Enum.IsDefined(typeof(MyEnum), key ) uses reflection, doesn't understand [Flags]
- [Flags] enum common operations (using System.Security.AccessControl.FileSystemRights for acls):
private static bool HasFlag(FileSystemRights rights, FileSystemRights flag)
{
return (flag & rights) == flag;
}
private static FileSystemRights AddFlag(FileSystemRights rights, FileSystemRights flag)
{
return rights | flag;
}
private static FileSystemRights RemoveFlag(FileSystemRights rights, FileSystemRights flag)
{
return rights ^ flag;
}
Regex
Match "(12,3)" | Regex.Match(value, @"\(([\d]+),([\d]+)\)") |
Escaped "\(", group "()", digit shorthand "\d", repeated one or more "+", literal ",". |
Only printable ASCII | Regex.Replace(value, "[^\x20-\x7e]+", "") |
Unicode space to ~ (x7f is delete) |
Is alphaNumeric with length | Regex.IsMatch(value, "^[\w\-]{8,20}$") |
Note \w is [A-Za-z0-9_] (includes underscore) |
dd-MM-yyyy HH:mm | Regex.IsMatch(value, "^([012]\\d|[3][0-1])[- /.]([0]\\d|[1][0-2])[- /.](19|20)\\d{2} ([01]\\d|[2][0-3])\:([0-5]\\d)$") |
Using (|) conditionals to limit numbers, and for variable date delimiters. |
For html (Source: Phil Haack):
private static void HtmlTagsViaRegexMatches()
{
string html = "<P><A href=page.html>Page</A>";
Regex regex =
new Regex(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>",
RegexOptions.Singleline);
MatchCollection matches = regex.Matches(html);
foreach (Match match in matches)
{
//matches <P>, <A href=page.html>, </A>
Debug.WriteLine(match.Value + " found at " + match.Index);
}
}
private static void HtmlTagsViaMatchEvaluator()
{
string html = "<P><A href=Page.html>Page</A>";
Regex rx = new Regex(@"<.*?>"); //simple form
string result = rx.Replace(html,
new MatchEvaluator(
delegate(Match m)
{
return m.Groups[0].Value.ToLower();
}
));
Assert.AreEqual("<p><a href=page.html>Page</a>", result);
}
Convert to/from Byte[]
var txt = System.Text.Encoding.UTF8.GetString(bytes);
var bytes = System.Text.Encoding.UTF8.GetBytes(mySteing);
BitConverter can only turn byte arrays to strings, not the other way (it just takes numeric types): var bytes = BitConverter.GetBytes(myInt);
You may have BOM (byte order mark) errors ("Data at the root level is invalid. Line 1, position 1"), in which case use a StreamReader:
//3rd ctor param is "detectEncodingFromByteOrderMarks"
var xml = new StreamReader(ms, Encoding.UTF8, true).ReadToEnd();
String to lines
using (var sr = new StringReader(lines))
{
string line;
while ((line = sr.ReadLine()) != null)
{
ParseLine(line);
}
}
Streams
String to stream
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(txt)))
{
//
}
Stream to string
string txt = null;
using (var reader = new StreamReader(stream))
{
txt = reader.ReadToEnd();
}
Serialize entity to xml string (XmlSerializer and XmlTestWriter)
var serializer = new XmlSerializer(typeof(Product));
var output = new StringWriter();
using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
{
serializer.Serialize(writer, product);
}
var txt = output.GetStringBuilder().ToString();