Username:   Password:  

Get Ip Address in Csharp

public static IPAddress GetLocalIPAddress()
        {
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    return ip;
                }
            }
 
            return IPAddress.None;
        }

Returns the ip address of the host in C#.

Tags

IP address C# CSharp

RenderPartialView in Controller MVC2

        StringBuilder RenderPartialView(string viewName,object model) {
 
            PartialViewResult partialResult = this.PartialView(viewName,model);
 
            ViewEngineResult engineResult = partialResult.ViewEngineCollection.FindPartialView(ControllerContext,viewName);
 
            if(engineResult == null)
                throw new ArgumentOutOfRangeException("FindPartialView() returned null - " + viewName);
            if(engineResult.View == null)
                throw new ArgumentOutOfRangeException("FindPartialView.View is null - " + viewName);
 
            IView view = engineResult.View;
 
            using(StringWriter writer = new StringWriter()) {
                using(HtmlTextWriter htmlWriter = new HtmlTextWriter(writer)) {
 
                    ViewContext vcontext = new ViewContext(
                        this.ControllerContext,
                        view,
                        this.ViewData,this.TempData,htmlWriter);
 
                    view.Render(vcontext,htmlWriter);
                    htmlWriter.Flush();
                    return writer.GetStringBuilder();
                }
            }
        }

Snippet to RenderPartialView in Controller MVC2

Tags

MVC ASP.NET

SynchronizedDictionary

/// Synchronized Dictionary
/// Dictionary that uses ReaderWriterLockSlim to syncronize all read and writes to the underlying Dictionary
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Core.Collections.Generic {
    /// <summary>
    /// Dictionary that uses ReaderWriterLockSlim to syncronize all read and writes to the underlying Dictionary
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    [Serializable]
    public class SynchronizedDictionary<TKey,TValue>:IDictionary<TKey,TValue>,IDisposable {
 
        Dictionary<TKey,TValue> _dictionary;
 
        [NonSerialized]
        ReaderWriterLockSlim _lock;
 
        public SynchronizedDictionary() {
            _dictionary = new Dictionary<TKey,TValue>();
        }
        public SynchronizedDictionary(IDictionary<TKey,TValue> dictionary) {
            _dictionary = new Dictionary<TKey,TValue>(dictionary);
        }
        public SynchronizedDictionary(IEqualityComparer<TKey> comparer) {
            _dictionary = new Dictionary<TKey,TValue>(comparer);
        }
        public SynchronizedDictionary(int capacity) {
            _dictionary = new Dictionary<TKey,TValue>(capacity);
        }
        public SynchronizedDictionary(IDictionary<TKey,TValue> dictionary,IEqualityComparer<TKey> comparer) {
            _dictionary = new Dictionary<TKey,TValue>(dictionary,comparer);
        }
        public SynchronizedDictionary(int capacity,IEqualityComparer<TKey> comparer) {
            _dictionary = new Dictionary<TKey,TValue>(capacity,comparer);
        }
        protected ReaderWriterLockSlim Lock {
            get {
                if(_lock == null) {
                    Interlocked.CompareExchange(ref _lock,new ReaderWriterLockSlim(),null);
                }
                return _lock;
            }
        }
        public void EnterReadLock() {
            Lock.EnterReadLock();
        }
        public void ExitReadLock() {
            Lock.ExitReadLock();
        }
        public void EnterWriteLock() {
            Lock.EnterWriteLock();
        }
        public void ExitWriteLock() {
            Lock.ExitWriteLock();
        }
        public void EnterUpgradeableReadLock() {
            Lock.EnterUpgradeableReadLock();
        }
        public void ExitUpgradeableReadLock() {
            Lock.ExitUpgradeableReadLock();
        }
        protected Dictionary<TKey,TValue> Dictionary {
            get {
                return _dictionary;
            }
        }
        public TValue GetAdd(TKey key,Func<TValue> addfunction) {
 
            if(addfunction == null)
                throw new ArgumentNullException("Func<TValue> addfunction");
 
            try {
                EnterUpgradeableReadLock();
 
                if(!_dictionary.ContainsKey(key)) {
                    try {
                        EnterWriteLock();
 
                        TValue value = addfunction();
 
                        _dictionary.Add(key,value);
                        return value;
                    }
                    finally {
                        ExitWriteLock();
                    }
                }
                else {
                    return _dictionary[key];
                }
            }
            finally {
                ExitUpgradeableReadLock();
            }
        }
        public void Add(TKey key,TValue value) {
            try {
                EnterWriteLock();
                _dictionary.Add(key,value);
            }
            finally {
                ExitWriteLock();
            }
        }
        public void Add(KeyValuePair<TKey,TValue> item) {
            try {
                EnterWriteLock();
                _dictionary.Add(item.Key,item.Value);
            }
            finally {
                ExitWriteLock();
            }
        }
        public bool Add(TKey key,TValue value,bool throwOnNotFound) {
            try {
                EnterUpgradeableReadLock();
                if(!_dictionary.ContainsKey(key)) {
                    try {
                        EnterWriteLock();
                        _dictionary.Add(key,value);
                        return true;
                    }
                    finally {
                        ExitWriteLock();
                    }
                }
                else {
                    if(throwOnNotFound)
                        throw new ArgumentNullException();
                    else
                        return false;
                }
            }
            finally {
                ExitUpgradeableReadLock();
            }
        }
        public bool ContainsKey(TKey key) {
            try {
                EnterReadLock();
                return _dictionary.ContainsKey(key);
            }
            finally {
                ExitReadLock();
            }
        }
        public bool Contains(KeyValuePair<TKey,TValue> item) {
            try {
                EnterReadLock();
                return _dictionary.Contains(item);
            }
            finally {
                ExitReadLock();
            }
        }
        public TKey[] KeysToArray() {
            try {
                EnterReadLock();
                return _dictionary.Keys.ToArray();
            }
            finally {
                ExitReadLock();
            }
        }
        public ICollection<TKey> Keys {
            get {
                return _dictionary.Keys;
            }
        }
        public bool Remove(TKey key) {
            try {
                EnterWriteLock();
                return _dictionary.Remove(key);
            }
            finally {
                ExitWriteLock();
            }
        }
        public bool Remove(KeyValuePair<TKey,TValue> item) {
            try {
                EnterWriteLock();
                return _dictionary.Remove(item.Key);
            }
            finally {
                ExitWriteLock();
            }
        }
        public bool TryGetValue(TKey key,out TValue value) {
            try {
                EnterReadLock();
                return _dictionary.TryGetValue(key,out value);
            }
            finally {
                ExitReadLock();
            }
        }
        public TValue[] ValuesToArray() {
            try {
                EnterReadLock();
                return _dictionary.Values.ToArray();
            }
            finally {
                ExitReadLock();
            }
        }
        public ICollection<TValue> Values {
            get {
                return _dictionary.Values;
            }
        }
 
        public TValue this[TKey key] {
            get {
                try {
                    EnterReadLock();
                    return _dictionary[key];
                }
                finally {
                    ExitReadLock();
                }
            }
            set {
                try {
                    EnterWriteLock();
                    _dictionary[key] = value;
                }
                finally {
                    ExitWriteLock();
                }
            }
        }
        public void Clear() {
            try {
                EnterWriteLock();
                _dictionary.Clear();
            }
            finally {
                ExitWriteLock();
            }
        }
        public void CopyTo(KeyValuePair<TKey,TValue>[] array,int arrayIndex) {
            try {
                EnterReadLock();
 
                for(int i = 0;i < _dictionary.Count;i++) {
                    array.SetValue(_dictionary.ElementAt(i),arrayIndex);
                }
            }
            finally {
                ExitReadLock();
            }
        }
        public int Count {
            get {
                try {
                    EnterReadLock();
                    return _dictionary.Count;
                }
                finally {
                    ExitReadLock();
                }
            }
        }
        public bool IsReadOnly {
            get {
                return false;
            }
        }
        public bool IsSynchronized {
            get {
                return true;
            }
        }
        public IEnumerator<KeyValuePair<TKey,TValue>> GetEnumerator() {
            EnterReadLock();
            try {
                return _dictionary.GetEnumerator();
            }
            finally {
                ExitReadLock();
            }
        }
        IEnumerator IEnumerable.GetEnumerator() {
            return this.GetEnumerator();
        }
 
        protected bool IsDisposed { get; set; }
        public virtual void Dispose() {
            if(IsDisposed)
                throw new ObjectDisposedException(this.GetType().Name);
            try {
                this.Dispose(true);
            }
            finally {
                GC.SuppressFinalize(this);
            }
        }
        protected virtual void Dispose(bool disposing) {
            try {
                if(!IsDisposed) {
                    if(disposing) {
                        if(_lock != null) {
                            _lock.Dispose();
                            _lock = null;
                        }
                    }
                }
            }
            finally {
                this.IsDisposed = true;
            }
        }
        //Only add Finalizer in you need to dispose of resources with out call Dispose() directly
        ~SynchronizedDictionary() {
            Dispose(!IsDisposed);
        }
    }
}

Dictionary that uses ReaderWriterLockSlim to syncronize all read and writes to the underlying Dictionary

Tags

Threading Collections

Read File Permissions in C#

String fullPath = Path.GetFullPathInternal(path);
// For security check, path should be resolved to an absolute path.
new System.Security.Permissions.FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullPath }, false, false ).Demand(); 

Tags

permissions files c#

Get current UTC Time in C#

DateTime.Now.ToUniversalTime();

Tags

UTC time C#

Search and replace string recursively in C#

static void ProcessDir(string path, string search, string replace)
{
    // First access subdirectories
    string[] subDirs = Directory.GetDirectories(path);
 
    foreach (string curSubDir in subDirs)
    {
        ProcessDir(Path.Combine(path, curSubDir));
    }
 
    // Now process files
    string[] files = Directory.GetFiles(path, "*.txt");
 
    foreach(string curFile in files) {
        ProcessFile(Path.Combine(path, curFile), search, replace);
    }
}
 
private static void ProcessFile(string path, string search, string replace)
{
    StreamReader input = new StreamReader(path);
    string content = input.ReadToEnd();
    input.Close();
 
    content = Regex.Replace(content, search, replace);
 
    try
    {
        StreamWriter output = new StreamWriter(path);
        output.Write(content);
        output.Close();
    }
    catch (IOException)
    {
        Console.WriteLine("Skipping file " + path);
        return;
    }
}

Searches recursively for *.txt files in a directory and subdirectories and replaces all occurences of "string search" with "string replace"

Tags

search replace C# CSharp .NET Regex Regual Expressions

Get working directory in a C# console app

System.IO.Path.GetDirectory(
  System.Reflection.Assembly.GetExecutingAssembly().Location
);

Tags

c# csharp console application path

Fetch unhandled exceptions in C#

using System;
 
namespace SomeNamespace {
 
	[STAThread]
	static class Program
	{
		private static void Main()
        {
			// Trace all unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(Program.OnUnhandledException);
		}
	}
 
	///<summary>
	/// Event handler for unhandled exceptions
	///</summary>
	private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
	{
		Exception exceptionObject = e.ExceptionObject as Exception;
		// Do something with the unhandled exception here
	}
}

Registers an event handler for all unhandled exceptions that are thrown during runtime.

Tags

csharp C# .NET unhandled exceptions

Store settings in XML file in C#

using System;
using System.IO;
using System.Xml;
 
namespace SomeNamespace
{
    static class SettingsProvider
    {
        private const string CONFIG_FILE = "config.xml";
        private static XmlDocument _xmlDoc = null;
 
 
        private static string ConfigPath
        {
            get { return Program.ApplicationFolder + @"\" + CONFIG_FILE; }
        }
 
 
        public static void Save(string key, string value)
        {
            XmlNode node = _xmlDoc.SelectSingleNode("./config/" + key);
 
            if (node != null)
            {
                node.InnerText = value;
                Save();
            }
            else
            {
                // XML node doesnt exist thus create a new one
                Get(key, value);
            }
        }
 
        /// <summary>
        /// Gets a value of the settings. If the setting does not exist, defaultValue is returned.
        /// </summary>
        public static string Get(string key, string defaultValue)
        {
            if (_xmlDoc == null)
            {
                _xmlDoc = new XmlDocument();
 
                // Load config.xml
                string fullPath = SettingsProvider.ConfigPath;
 
                if (!File.Exists(fullPath))
                {
                    // Xml declaration
                    XmlDeclaration declaration = _xmlDoc.CreateXmlDeclaration("1.0", null, null);
                    _xmlDoc.AppendChild(declaration);
 
                    // Root node <config>
                    XmlElement rootNode = _xmlDoc.CreateElement("config");
                    _xmlDoc.AppendChild(rootNode);
 
                    Save();
                }
                else
                {
                    _xmlDoc.Load(fullPath);
                }
            }
 
            XmlNode node = _xmlDoc.SelectSingleNode("./config/" + key);
 
            if (node != null)
            {
                return node.InnerText;
            }
            else
            {
                // Add default value
                XmlElement newSetting = _xmlDoc.CreateElement(key);
                newSetting.InnerText = defaultValue;
                _xmlDoc.ChildNodes[1].AppendChild(newSetting);
 
                Save();
 
                return defaultValue;
            }
        }
 
        public static void Save()
        {
            if (_xmlDoc != null)
            {
                _xmlDoc.Save(SettingsProvider.ConfigPath);
            }
        }
    }
}
 

Provides access to key/value pairs stored in a config file in XML format.

Tags

C# CSharp .NET config file XML Settings provider

Simple logfile singleton in CSharp

using System;
using System.Text;
using System.IO;
 
namespace SomeNamespace
{
    sealed class SimpleLogger : IDisposable
    {
		/// <summary>
		/// Singleton instance
		/// </summary>
        private static readonly SimpleLogger _instance = new Logger();
        private readonly string _logFilePath;
        private readonly FileStream _logFileStream;
 
 
        public static SimpleLogger Instance
        {
            get { return _instance; }
        }
 
        private SimpleLogger()
        {
            _logFilePath = Program.ApplicationFolder + @"\bithub.log";
            _logFileStream = new FileStream(_logFilePath, FileMode.Append);
        }
 
        public void Dispose()
        {
            if (_logFileStream != null)
            {
                _logFileStream.Flush();
                _logFileStream.Close();
            }
        }
 
		/// <summary>
		/// Creates logfile entry in the following form: 01.01.1970 00:00 -:- MESSAGE
		/// </summary>
        public void WriteLine(string message)
        {
            message = DateTime.Now.ToString("g") + " -:- " + message + Environment.NewLine;
            Byte[] output = new UTF8Encoding(true).GetBytes(message);
            _logFileStream.Write(output, 0, output.Length);
            _logFileStream.Flush();
        }
    }
}
 

A simple logging class for creating logfiles. Implemented as a singleton pattern.

Tags

C# CSharp .NET logger logfile simple

Count lines of a file

/// <summary>
/// Counts the lines of a File.
/// </summary>
/// <param name="fileToCount">The file to count.</param>
/// <returns>lines of a File</returns>
private static int CountLines(string fileToCount)
{
    int counter = 0;
    using (StreamReader countReader = new StreamReader(fileToCount))
    {
        while (countReader.ReadLine() != null)
            counter++;
    }
    return counter;
}
 

Tags

C# CSharp .NET count lines files

Move file to trashbin

[DllImport("shell32.dll", CharSet = CharSet.Auto)]
static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
 
private void MoveToBin(string filePath)
{
    SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();
    fileop.wFunc = FO_DELETE;
    fileop.pFrom = filePath + '\0' + '\0';
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
    SHFileOperation(ref fileop);
}
 
private const int FO_DELETE = 3;
private const int FOF_ALLOWUNDO = 0x40;
private const int FOF_NOCONFIRMATION = 0x0010;
 
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
{
    public IntPtr hwnd;
    [MarshalAs(UnmanagedType.U4)]
    public int wFunc;
    public string pFrom;
    public string pTo;
    public short fFlags;
    [MarshalAs(UnmanagedType.Bool)]
    public bool fAnyOperationsAborted;
    public IntPtr hNameMappings;
    public string lpszProgressTitle;
}
 

Moves a file to the windows trashbin.

Tags

trashbin C# Csharp .NET

Save text file in ArrayList

using System.Collections;
 
private ArrayList TextToArraylist(string Pfad)
{
  ArrayList Text = new ArrayList();  
  System.IO.StreamReader SR = new System.IO.StreamReader(Pfad); 
  while ( SR.Peek() > -1)
  {
    Text.Add(SR.ReadLine());
  }
  SR.Close();
  return Text;
}
 

Loads a text file into an ArrayList

Tags

Csharp C# ArrayList

Get application directory path

using System.IO;
using System.Windows.Forms;
 
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
 

Gets the path of the application directory, where the assembly is running in.

Tags

CSharp C# path

Stateless SQL

using System;
using System.Text;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
 
namespace sample
{
    class StateLess
    {
        public StateLess()
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "...";
            SqlCommand cmd = new SqlCommand("SELECT * FROM `TABLE_NAME` WHERE 1;", con);
 
            // Prepare data container
            DataSet ds = new DataSet();
 
            // Fetch data
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds); // Opens and closes connection itself
 
            // Iterate through rows
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                ConsoleWriteLine(row["ROW_NAME"]);
            }
        }
    }
}

A simple example for stateless SQL commands in .NET and ADO.NET. Replace "TABLE_NAME" and "ROW_NAME" with your own values.

Tags

C# ADO.NET .NET CSharp SQL

Webrequest example

using System.Net;
using System.IO;
using System.Text;
 
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
 
byte[] recvBuffer = new byte[8192];
StringBuilder htmlOutput = new StringBuilder();
int count;
 
do
{
    count = resStream.Read(recvBuffer, 0, recvBuffer.Length);
 
    if (count != 0)
    {
        htmlOutput.Append(Encoding.ASCII.GetString(recvBuffer, 0, count));
    }
} while (count > 0);
 
txtHtmlOutput.Text = htmlOutput.ToString();

This example opens google.com, reads the site contents and saves those in a string.

Tags

C# CSharp webrequest

CSV reader

using System;
using System.Collections;
using System.Data;
using System.Text;
using System.IO;
 
namespace SomeNamespace
{
    static class CsvReader
    {
        public static DataTable Parse(TextReader stream, bool headers)
        {
            DataTable table = new DataTable();
 
            CsvStream csv = new CsvStream(stream);
            string[] row = csv.GetNextRow();
            if (row == null)
                return null;
            if (headers)
            {
                foreach (string header in row)
                {
                    if (header != null && header.Length > 0 && !table.Columns.Contains(header))
                        table.Columns.Add(header, typeof(string));
                    else
                        table.Columns.Add(GetNextColumnHeader(table), typeof(string));
                }
                row = csv.GetNextRow();
            }
            while (row != null)
            {
                while (row.Length > table.Columns.Count)
                    table.Columns.Add(GetNextColumnHeader(table), typeof(string));
                table.Rows.Add(row);
                row = csv.GetNextRow();
            }
            return table;
        }
 
        private static string GetNextColumnHeader(DataTable table)
        {
            int c = 1;
            while (true)
            {
                string h = "Column" + c++;
                if (!table.Columns.Contains(h))
                    return h;
            }
        }
    }
 
    class CsvStream
    {
        private TextReader stream;                 
 
        public CsvStream(TextReader s)
        {
            this.stream = s;
        }
 
        public string[] GetNextRow()
        {
            ArrayList row = new ArrayList();
 
            while (true)
            {
                string item = GetNextItem();
                if (item == null)
                        return row.Count == 0 ? null : (string[])row.ToArray(typeof(string));
                row.Add(item);
            }
        }
 
        private bool EOS = false;
        private bool EOL = false;
 
        private string GetNextItem()
        {
            if (EOL)
            {
                // previous item was last in line, start new line
                EOL = false;
                return null;
            }
 
            bool quoted = false;
            bool predata = true;
            bool postdata = false;
 
            StringBuilder item = new StringBuilder();
 
            while (true)
            {
                char c = GetNextChar(true);
                if (EOS)
                        return item.Length > 0 ? item.ToString() : null;
 
                if ((postdata || !quoted) && c == ';')
                    // end of item, return
                    return item.ToString();
 
                if ((predata || postdata || !quoted) && (c == '\x0A' || c == '\x0D'))
                {
                    // we are at the end of the line, eat newline characters and exit
                    EOL = true;
                    if (c == '\x0D' && GetNextChar(false) == '\x0A')
                            // new line sequence is 0D0A
                            GetNextChar(true);
                    return item.ToString();
                }
 
                if (predata && c == ' ')
                    // whitespace preceeding data, discard
                    continue;
 
                if (predata && c == '"')
                {
                    // quoted data is starting
                    quoted = true;
                    predata = false;
                    continue;
                }
 
                if (predata)
                {
                    // data is starting without quotes
                    predata = false;
                    item.Append(c);
                    continue;
                }
 
                if (c == '"' && quoted)
                {
                    if (GetNextChar(false) == '"')
                            // double quotes within quoted string means add a quote       
                            item.Append(GetNextChar(true));
                    else
                            // end-quote reached
                            postdata = true;
                    continue;
                }
 
                // all cases covered, character must be data
                item.Append(c);
            }
        }
 
        private char[] buffer = new char[4096];
        private int pos = 0;
        private int length = 0;
 
        private char GetNextChar(bool eat)
        {
            if (pos >= length)
            {
                    length = stream.ReadBlock(buffer, 0, buffer.Length);
                    if (length == 0)
                    {
                            EOS = true;
                            return '\0';
                    }
                    pos = 0;
            }
 
            if (eat)
                    return buffer[pos++];
            else
                    return buffer[pos];
        }
    }
}
 
 
 

Class for accessing and reading CSV (comma seperated values) files.

Tags

C# CSharp CSV reader

Access forms by a thread

delegate void WriteStatusCallback(string statusMsg); 
 
public void WriteStatus(string statusMsg)
{
    if (InvokeRequired)
    {
        Invoke(new WriteStatusCallback(WriteStatus), new Object[] { statusMsg });
    }
    else
    {
        // Access Windows forms control
    }
}

Accessing Windows forms controls needs special handling by the Invoke() function.

Tags

C# CSharp threads invoke windows forms

File locks in CSharp

string filename = "c:\\sample.htm";
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, 
FileShare.None); //locks file
stream.Close(); //unlocks file
 
// or another variant:
 
string filename = "c:\\sample.htm";
FileStream stream = File.Open(filename, FileMode.Open);
stream.Lock(0, stream.Length); //locks file  
stream.Unlock(0, stream.Length); //unlocks file

Locks a file for exclusive use.

Tags

C# CSharp file locks filelocking

Example for serialization

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null) return null;
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);
    return ms.ToArray();
}
 
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);
    return obj;
}

Simple example for converting objects into byte arrays aka serialization. For custom classes add [Serializable] attribute to enable serialization.

Tags

C# CSharp serialization array

UNIX timestamp

public static int UnixTimestamp()
{
    DateTime time = new DateTime(0x7b2, 1, 1);
    DateTime now = DateTime.Now;
    TimeSpan span = new TimeSpan(now.Ticks - time.Ticks);
    TimeSpan span2 = new TimeSpan(DateTime.UtcNow.Ticks - DateTime.Now.Ticks);
    return Convert.ToInt32((double) (span.TotalSeconds + span2.TotalSeconds));
}

Function for getting the current UNIX timestamp on a windows based machine.

Tags

C# Sharp time unix

Form fade out

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Form FormToFadeOut = (Form)sender;
    float Step = (float)(100f / 20);
    float Opacity = 100f;
 
    for (byte b = 0; b < 10; b++)
    {
        FormToFadeOut.Opacity = Opacity / 100;
        FormToFadeOut.Refresh();
        Opacity -= Step;
    }
}

As the title says, fades out a form. Replace FormToFadeOut with the form name you want to fade out.

Tags

C# CSharp Forms fade out

Simple file dialog

String[] showFileDialog()
{
    OpenFileDialog dialog = new OpenFileDialog();
 
    dialog.InitialDirectory = ".";
    // Preselect .txt files
    dialog.Filter = "Txt-Dateien|*.txt";
    dialog.FilterIndex = 1;
    dialog.Multiselect = false;
    dialog.RestoreDirectory = true;
 
    if (dialog.ShowDialog() == DialogResult.OK)
    {
        return dialog.FileNames[0];
    }
}

Shows a simple dialog to pick a file from the local filesystem. In this snippet, only .txt files are preselected.

Tags

C# CSharp file dialog

Basic event handling

class EventSender
{
    public delegate void testEventHandler(object sender, EventArgs e);
 
    public event testEventHandler testEvent;
 
    public void makeEvent()
    {
		// Trigger event
        testEvent(this, new EventArgs());
    }
}
 
 
class EventReceiver
{
    EventSender eventSender;
 
    private void registerEvent()
    {
        eventSender.testEvent += new EventSender.testEventHandler(testEventHandler);
    }
 
    private void testEventHandler(object sender, EventArgs e)
    {
		// Event is handled here
    }
}

This piece of code implements a basic event handler. Code should be self explanatory.

Tags

C# CSharp eventhandler howto events