Wednesday, April 29, 2009

Create a Checked Listbox with Key/Values Pairs

Sometimes, there is a need to display one set of strings in a checked listbox and use a different one in your code. For example, a user selects 'Washington', and you want the code to use 'WA'.
If that's the case, a Dictionary object will suit your needs. First, let's start with building a Dictionary:


public Dictionary<string, string> dicStates = new Dictionary<string, string>
        {
            { "Washington", "WA"},
            {"New York", "NY"},
            {"Texas", "TX"}
        };


Strings to be displayed in the checked listbox become dictionary keys, and strings to be used in your code become dictionary values.

Then, in your form constructor you populate the CheckedListBox:
foreach (var item in dicStates )
{
    clb1.Items.Add(item.Key);
}



To capture user-selected values, use the following code:


foreach (var key in clb1.CheckedItems)
{
    string val = string.Empty;
    dicStates .TryGetValue(key.ToString(), out val);
}


The string val will hold the Dictionary value - WA, NY or TX depending on the user selection.

Friday, April 3, 2009

Files and Directories

To get information about a directory, first you need to create a DirectoryInfo object:
string strPath = @"C:\Temp\Test1"
DirectoryInfo dInfo = new DirectoryInfo(strPath);

dInfo.Name gets the directory name (Test1)
dInfo.Parent gets the parent directory name (Temp)
dInfo.FullName gets the full path (C:\Temp\Test1)


Create a directory if it does not exist:

if (!dInfo.Exists)
dInfo.Create();


To get an array of subdirectories use:
DirectoryInfo[] subDirInfo = dInfo.GetDirectories();

Get File Size:

FileInfo fileInfo = new FileInfo(strPath);
Console.WriteLine(fileInfo.Length);


Get a directory name from a file name:

FileInfo fileInfo = new FileInfo("C:\\MyFolder\\MyFile.exe");
Console.WriteLine(fileInfo.DirectoryName);

To change file timestamp after FileStream write use the following methods

File.SetCreationTime(filepath, DateTime);
File.SetLastWriteTime(filepath, DateTime);


Surround Commas with Double Quotes

This is how you surround commas with double quotes.
string str = "This, is, a string, with multiple, commas";
str = str.Replace(",", "\",\"");
The result will look like this:

This"," is"," a string"," with multiple"," commas

Thursday, April 2, 2009

Method to Surround Substrings with Single Quotes

If you have a long string containing substrings delimited by commas, you may need to surround each piece with single commas.
For example: trains, planes, automobiles.
In such a case, this method may come in handy:

public static string delimitString(string str){
string[] arr = str.Split(',');
StringBuilder sb = new StringBuilder();
foreach (string s in arr)
{
sb.Append("'" + s.Trim() + "',");
}
sb.Length--;
return sb.ToString();
}

The resulting string will look like this: 'trains', 'planes', 'automobiles'