Get current UTC Time in C#
DateTime.Now.ToUniversalTime();
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"
System.IO.Path.GetDirectory( System.Reflection.Assembly.GetExecutingAssembly().Location );
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.
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.
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.
/// <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; }
[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.
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
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.
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.
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.
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.
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.
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.
// 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.
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.
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.
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.
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.
Most popular snippets