Archive for August 2013

Simple c# StringBuilder example

A simple example of using the StringBuilder to concat strings.

StringBuilder mySB = new StringBuilder();
mySB.Append("line 1");
mySB.Append("line 2");
mySB.Append("line 3");
Console.WriteLine(mySB.ToString());

String formating within C#

Below is an example of using string formating to print a time

int h = 12;
int m = 13;
int s = 14;
string myString = string.Format("{0}:{1}:{2}", h, m, s);
Console.WriteLine(myString);

To format a number to two decimal places, you could use the string format.

double s = 14.123;
string myString = string.Format("{0:0.00}", s);
Console.WriteLine(myString);

Reading a file with C#

Reading a text file line by line in C#. Dont forget to include using System.IO;

StreamReader myReader = new StreamReader(@"c:\test.txt");
string line = "";
while (line != null)
{
   line = myReader.ReadLine();
   Console.WriteLine(line);
}

You can read all the text within a file using the ReadAllText function.

string filename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\test.txt";
string content = File.ReadAllText(filename);
MessageBox.Show(content);

Explicit Conversion of a string to Integer using c#

Explicit Conversion of a string to Integer, sometimes known as cast.

string myString = "7";
int myInt = int.Parse(myString);
Console.WriteLine(myInt);

The above code will fail if the string can not be converted to a integer. For example if myString=”Seven”, the code would fail. To avoid this problem use TryParse.

string myString = "Seven";
int myInt = 0;
if (int.TryParse(myString, out myInt) == true)
{
   Console.WriteLine("String converted");
}
else
{
   Console.WriteLine("String NOT converted");
}
Console.WriteLine(myInt);