June 2009 Entries
If you ever need to convert Hex data to readable strings or the reverse, try the following methods:
private static readonly char[] HexChars = "0123456789ABCDEF".ToCharArray();
private static string ConvertToHex(string ascii)
{
if (ascii == null) return null;
if (ascii == "") return "";
byte[] bytes = Encoding.UTF8.GetBytes(ascii);
StringBuilder converted = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
converted.Append(HexChars[b >> 4]);
converted.Append(HexChars[b & 0xf]);
}
return converted.ToString();
}
private static string ConvertFromHex(string hex)
{
if (hex == null) return null;
if (hex == "") return "";
if (hex.Length % 2 != 0)
throw new ApplicationException(
"hex string length should be divisble by 2: " +...
Here’s how you can read a CSV file using Regular Expressions in .Net:
public static DataTable GetDataTableFromCsvFile(string file)
{
// Where the CSV data goes
DataTable dt = new DataTable("CsvData");
// The pattern used to parse the CSV
const string csvPattern = ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))";
Regex csvRegex = new Regex(csvPattern);
// Read all lines in the file
// (not great for large files)
string[] fileLines = File.ReadAllLines(file);
// Get the column headers
// (assumes first row has headers and that
// each column contains string values and
// that each column name is unique)
Dictionary<int, string> headers = new Dictionary<int, string>();
...
Reading a comma delimited is quite simple with an OleDbDataAdapter and Jet 4.0:
private static DataTable ReadCsvFileViaJetOleDb(string file)
{
string connection =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
Path.GetDirectoryName(file) +
"\\\";Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";
string query = "SELECT * FROM " + file;
DataTable dt = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(query, connection))
da.Fill(dt);
return dt;
}
However, you have to remember a few caveats:
Commas may not be your default delimiter for your UI culture
Only txt, csv, asc, and tab are acceptable file extensions
You can't have more than one period in a file name, e.g. myfile.test.csv won't...
The July 2009 issue of TechNet Magazine is out on the website. Check out my IT Toolbox column here:
July 2009 TechNet Magazine IT Toolbox
In this issue I cover:
ObserveIT Express: Audit your Users' Sessions
Mouse Tracks 2009 Enterprise Edition: Help Desk Inventory and Systems Tracking Tool
Book Review: Windows Server 2008 Security Resource Kit
Duplicate File Remover: Clean Up Your Systems
Check it out and let me know what you think!
And if you have a tool you want to see me review, suggest it to me: tntools@microsoft.com.