Archive for the ‘C#’ Category.

Enumerations with tryParse in C#

Here is an example of using enum with a tryParse. The program asks the user to enter a new state. The tryParse then attempts to convert the input into a enum.

// define current state
MyState currentState = MyState.off;
            
// get value from user
Console.WriteLine("Please enter the new state");
string input = Console.ReadLine();

if (Enum.TryParse(input, out currentState) == false)
{
    Console.WriteLine("Unable to compute input");
}
Console.WriteLine("Current state " + currentState);

Console.WriteLine("=== Finished ===");
Console.ReadLine();
}

enum MyState
{
on,
off,
idle
}

Adding days to a DateTime in C#

Add seven days to the current time.

DateTime start = DateTime.Now;
Console.WriteLine("Start date = " + start.ToString("dd/MM/yyyy hh:mm:ss"));
DateTime end = start.AddDays(7);
Console.WriteLine("End date = " + end.ToString("dd/MM/yyyy hh:mm:ss"));

Other methods for defining a DateTime object

DateTime start = DateTime.Parse("23/01/1984 01:02:03");
DateTime start = new DateTime(1984, 01, 23, 01, 02, 03);

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);

Get Web Page Content as a String with C#

This function dowloads the html content of a webpage and returns the content as a string.

public static string GetWebPageAsString(string url) {
    HttpWebRequest httpWebRequest =(HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    Stream stream = httpWebResponse.GetResponseStream();
    StreamReader streamReader = new StreamReader(stream, Encoding.ASCII);
    return streamReader.ReadToEnd();
}

Recursive delete files and folders using C#

This function will Recursively delete all files and folders.

private void DeleteAllFiles(string sPath)
{
    foreach(string strFile in Directory.GetFiles(sPath))
    {
        File.Delete(strFile);
    }
    foreach (string strDir in Directory.GetDirectories(sPath))
    {
        DeleteAllFiles(strDir);
    }
    Directory.Delete(sPath);
}

Create a autocompleting textbox using C#

The code example below creates an autocompleting textbox, with the possible values Andy, Andrew, Dylan and Kyle.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace autoComplete
{
    public partial class Form1 : Form
    {
        AutoCompleteStringCollection nameCollection = new AutoCompleteStringCollection();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            nameCollection.Add("Andy");
            nameCollection.Add("Andrew");
            nameCollection.Add("Dylan");
            nameCollection.Add("Kyle");

            txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
            txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtName.AutoCompleteCustomSource = nameCollection;
        }
    }
}

Create arraylist

Create an ArrayList and add three elements.

using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList list = new ArrayList();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
    }
}