====== C# code snippets ======
===== Trabajo con datos =====
==== Conversiones ====
=== De byte a String ===
new System.Text.ASCIIEncoding().GetString( xxxxxxxxxxxx );
=== De String a byte ===
new System.Text.ASCIIEncoding().GetBytes( xxxxxxxxxxxx );
=== De unicode a String ===
Encoding.UTF8.GetString(myByteArray))
==== Arrays ====
* Podemos limpiar un array con el método estático ''Array.Clear''.
* Los elementos ''IQueryable<>'', esos que provienen de consultas con LINQ, tienen métodos tan útiles como ''ToList'' o ''ToArray''.
==== Fechas ====
=== Diferencia de fechas ===
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
System.Console.WriteLine("Difference in days: {0} ", differenceInDays);
==== Trabajar con ficheros ====
=== Leer ===
String sFile = @"c:\matriu2.txt";
StreamReader re = File.OpenText(sFile);
string input = null;
while ((input = re.ReadLine()) != null)
{}
re.Close();
=== Escribir ===
FileInfo t = new FileInfo(@"c:\matriu3.txt");
StreamWriter sw = t.CreateText();
sw.WriteLine("hola");
sw.Close();
Otra alternativa de declaración:
StreamWriter sw = new StreamWriter(File.Open(sFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
=== Escribir en UTF8 ===
System.IO.TextWriter tw = new System.IO.StreamWriter(
new System.IO.FileStream(path + "\\index.html", System.IO.FileMode.Create),
System.Text.Encoding.UTF8);
tw.Write(body);
tw.Close();
==== XML ====
Abrir archivos para lectura, con la referencia ''System.Xml'' agregada:
XmlDocument doc = new XmlDocument();
doc.Load(path);
Coger nodos por nombre:
XmlNode mainNode = doc.GetElementsByTagName("kvtml")[0];
Coger nodos hijo:
XmlNodeList nodes = mainNode.ChildNodes;
Coger texto interno:
foreach (XmlNode node in nodes)
{
lang1 = node.ChildNodes[0].InnerText;
}
==== Expresiones regulares ====
=== Eliminar las tags de un texto ===
using System.Text.RegularExpressions;
public string Strip(string text)
{
return Regex.Replace(text, @”<(.|\n)*?>”, string.Empty);
}
==== Descargar archivos de internet ====
System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadFile("http://url/imagen.jpg", "c:\\img.jpg");
===== Trabajo con el Sistema Operativo =====
==== Windows.Forms ====
=== Asignar un DataList a un combo ===
DataTable list = new DataTable();
list.Columns.Add(new DataColumn("telf", typeof(string)));
list.Columns.Add(new DataColumn("Id", typeof(int)));
for(int w=0;w<(ret.filas);w++) {
list.Rows.Add(list.NewRow());
list.Rows[w][0] = "("+ret.getCell(w,ret.getNumCell("tel_area"))+")(" +
ret.getCell(w,ret.getNumCell("tel_region"))+") "
+ret.getCell(w,ret.getNumCell("tel_numero"));
list.Rows[w][1] = System.Convert.ToInt32(ret.getCell(w,
ret.getNumCell("tel_sectel")));
}
this.cmbInt.DataSource = list;
this.cmbInt.DisplayMember = "telf";
this.cmbInt.ValueMember = "Id";
=== Saber control activo en un formulario ===
private void DisplayNameOfActiveControl() {
label1.Text = this.ActiveControl.Name;
}
=== Enlazar un array a un listbox ===
listBox1.DataSource = new string[] { "one", "two", "three" };
=== Llamar al click de un botón ===
private void button2_Click(object sender, System.EventArgs e) {
button1.PerformClick();
};
==== Creación de aplicaciones ====
=== Cambiar forma de ventana ===
protected override void OnPaint( System.Windows.Forms.PaintEventArgs e ) {
System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();
shape.AddEllipse(0, 0, this.Width, this.Height);
this.Region = new System.Drawing.Region(shape);
}
Podemos crear un formulario con forma mediante un png dibujado por código, drawImage, sobre un formulario sin bordes con un transparencekey.
=== Acceder al portapapeles ===
Clipboard.SetDataObject(textBox1.Text);
textBox1.Text = ClipBoard.GetDataObject();
=== Listar todos los archivos de un directorio ===
string[] str = Directory.GetFiles(“C:\\Windows”);
=== Menú contextual ===
private void Form1_Load(object sender, System.EventArgs e) {
System.Windows.Forms.ContextMenu contextMenu1;
contextMenu1 = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem menuItem1;
menuItem1 = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem2;
menuItem2 = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem3;
menuItem3 = new System.Windows.Forms.MenuItem();
contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {menuItem1, menuItem2, menuItem3});
menuItem1.Index = 0;
menuItem1.Text = "MenuItem1";
menuItem2.Index = 1;
menuItem2.Text = "MenuItem2";
menuItem3.Index = 2;
menuItem3.Text = "MenuItem3";
textBox1.ContextMenu = contextMenu1;
}
=== Seleccionar unas fechar en un control Calendar ===
private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e) {
DateTime startDate = e.Start;
startDate = startDate.AddDays(-(double)startDate.DayOfWeek);
monthCalendar1.SelectionStart = startDate;
monthCalendar1.SelectionEnd = startDate.AddDays(6);
}
=== Crear un botón no rectangular ===
public Form1() {
InitializeComponent();
myButtonObject myButton = new myButtonObject();
EventHandler myHandler = new EventHandler(myButton_Click);
myButton.Click += myHandler;
myButton.Location = new System.Drawing.Point(20, 20);
myButton.Size = new System.Drawing.Size(101, 101);
this.Controls.Add(myButton);
}
public class myButtonObject : UserControl {
protected override void OnPaint(PaintEventArgs e) {
Graphics graphics = e.Graphics;
Pen myPen = new Pen(Color.Black);
graphics.DrawEllipse(myPen, 0, 0, 100, 100);
myPen.Dispose();
}
public void myButton_Click(Object sender, System.EventArgs e) {
MessageBox.Show("Click");
}
}
==== Impresiones ====
=== Imprimir formulario ===
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern long BitBlt (IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
private Bitmap memoryImage;
private void CaptureScreen() {
Graphics mygraphics = this.CreateGraphics();
Size s = this.Size;
memoryImage = new Bitmap(s.Width, s.Height, mygraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
IntPtr dc1 = mygraphics.GetHdc();
IntPtr dc2 = memoryGraphics.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
mygraphics.ReleaseHdc(dc1);
memoryGraphics.ReleaseHdc(dc2);
}
private void printDocument1_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e) {
e.Graphics.DrawImage(memoryImage, 0, 0);
}
private void printButton_Click(System.Object sender, System.EventArgs e) {
CaptureScreen();
printDocument1.Print();
}
=== Imprimir un archivo de texto ===
System.IO.StreamReader fileToPrint;
System.Drawing.Font printFont;
private void printButton_Click(object sender, EventArgs e) {
string printPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
fileToPrint = new System.IO.StreamReader(printPath + @"\myFile.txt");
printFont = new System.Drawing.Font("Arial", 10);
printDocument1.Print();
fileToPrint.Close();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) {
float yPos = 0f;
int count = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
string line = null;
float linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics);
while (count < linesPerPage) {
line = fileToPrint.ReadLine();
if (line == null) {
break;
}
yPos = topMargin + count * printFont.GetHeight(e.Graphics);
e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
count++;
}
if (line != null) {
e.HasMorePages = true;
}
}
==== GDI+ y gráficos ====
=== Dar doble buffer a un formulario ===
this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint , true);
=== Dibujar texto vertical ===
private void DrawVerticalText() {
System.Drawing.Graphics formGraphics = this.CreateGraphics();
string drawString = "Sample Text";
System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 16);
System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
float x = 150.0f;
float y = 50.0f;
System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.DirectionVertical);
formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
drawFont.Dispose();
drawBrush.Dispose();
formGraphics.Dispose();
}
=== Crear un buffer de una imágen ===
// Define a pen
System.Drawing.Pen myPen = new Pen(new SolidBrush(Color.Black));
// Obtain the form's Graphics object.
System.Drawing.Graphics formGraphics = this.CreateGraphics();
// Define the bitmap for the buffer.
Bitmap bufferBitmap = new Bitmap(this.Width, this.Height);
System.Drawing.Graphics bufferGraphics = Graphics.FromImage(bufferBitmap);
// Draw into the buffer.
for (int x = 0; x < 300; x += 2)
bufferGraphics.DrawLine(myPen, 0, 0, x, 300);
// Copy the buffer to the form.
formGraphics.DrawImage(bufferBitmap, 0, 0);
// Clean up resources.
formGraphics.Dispose();
bufferGraphics.Dispose();
=== Cambiar una imágen de formato ===
// Load the image
Image myImage = Image.FromFile(@"C:\test.bmp");
// Save the image in JPEG format.
myImage.Save(@"C:\test.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
// Save the image in GIF format.
myImage.Save(@"C:\test.gif",System.Drawing.Imaging.ImageFormat.Gif);
// Save the image in PNG format.
myImage.Save(@"C:\test.png",System.Drawing.Imaging.ImageFormat.Png);
=== Crear un bitmap en tiempo de diseño ===
void CreateBitmap(){
System.Drawing.Bitmap flag = new System.Drawing.Bitmap(10, 10);
for( int x = 0; x < flag.Height; ++x )
for( int y = 0; y < flag.Width; ++y )
flag.SetPixel(x, y, Color.White);
for( int x = 0; x < flag.Height; ++x )
flag.SetPixel(x, x, Color.Red);
pictureBox1.Image = flag;
}
=== Pasar de un archivo imágen a byte[] ===
System.Windows.Forms.OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK) {
System.IO.FileStream stream = new System.IO.FileStream(dialog.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
stream.Close();
this.imgInBytes = buffer;
this.Carga();
}
Y del byte[] a un objeto Image:
if (this.imgInBytes != null) {
System.IO.MemoryStream stream = new System.IO.MemoryStream(this.imgInBytes, true);
this.Image = new System.Drawing.Bitmap(stream);
} else
this.Image = null;
=== Pasar de un Image a byte[] ===
System.IO.MemoryStream ms = new System.IO.MemoryStream();
this.Image.Save(ms, this.Image.RawFormat);
byte[] buffer = ms.GetBuffer();
ms.Close();
return buffer;
==== Otros ====
=== Hacer sonar un beep ===
using System.Runtime.InteropServices;
// Declare the interop API:
[DllImport("kernel32.dll")]
public static extern bool Beep(uint dwFreq, uint dwDuration);
// Make the interop call:
if (!Beep(440, 250))
// If the call the beep fails (if the computer has no sound card
// for example) display a warning dialog in its place.
MessageBox.Show("Alert.");
}
=== IP local y Nombre de Host ===
Poner en el textBox1 el nombre de host y en el 2 la IP (necesitamos incluir System.Net y System.Net.Sockets):
textBox1.Text = Dns.GetHostName();
IPAddress objIPAddress = new IPAddress(Dns.GetHostByName (Dns.GetHostName()).AddressList[2].Address);
textBox2.Text = objIPAddress.ToString();
Estamos cogiendo la 2ª IP de la máquina (AddressList[2]) podemos recorrer el array y recogerlas todas.
=== Mostrar una página en el IE ===
System.Diagnostics.Process.Start("C:\\Program Files\\Internet Explorer\\IExplore.exe", "www.microsoft.com");
=== Lanzar un programa a un fichero asociado ===
System.Diagnostics.Process.Start("c:\\test.txt");
La llamada a Process.Start requiere plena confianza de permisos en el SO (SecurityException).
=== Listar de Agregar y Quitar Programas mediante el uso del registro ===
static void Main(string[] args) {
string clave = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
object valor = "";
RegistryKey Reg = Registry.LocalMachine;
Reg = Reg.OpenSubKey(clave);
string [] SubKeyNames = Reg.GetSubKeyNames();
foreach (string str in SubKeyNames) {
RegistryKey tmpReg = Registry.LocalMachine;
tmpReg = tmpReg.OpenSubKey(clave + "\\" + str);
valor = tmpReg.GetValue("DisplayName");
if (valor != null)
Console.WriteLine(valor);
}
Console.ReadLine();
}
=== Recoger variables de entorno (ubicación escritorio, nombre de usuario actual…) ===
object s=System.Environment.GetEnvironmentVariables();
Environment.TickCount
Environtmen.SpecialFolder. ...
=== Saber si un ensamblado es debug o release ===
Assembly assm = Assembly.LoadFrom(filename);
bool found = assm.GetCustomAttributes(typeof(DebuggableAttribute), false).Length > 0;
buildType = found ? "Debug" : "Release";
=== Saber las fuentes instaladas en el sistema ===
System.Drawing.Text.InstalledFontCollection
=== Saber el usuario que está ejecutando el programa ===
Dentro de ''System.Security.Principal'' ...
WindowsIdentity id = WindowsIdentity.GetCurrent();
id.name;
=== Lanzar un comando y quedarte con su salida ===
public static string Command(string command, string pars)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = command;
process.StartInfo.Arguments = pars;
try
{
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
process.Start();
process.WaitForExit(Int32.MaxValue);
}
catch (Exception exc)
{
return exc.Message + "\n" + exc.StackTrace;
}
string ConsoleOutput = process.StandardOutput.ReadToEnd();
return ConsoleOutput;
}
=== Encriptar en MD5 ===
using System;
using System.Text;
using System.Security.Cryptography;
...
public string EncodePassword(string originalPassword)
{
Byte[] originalBytes;
Byte[] encodedBytes;
MD5 md5 = new MD5CryptoServiceProvider();
originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
encodedBytes = md5.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes);
}
... o ...
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(text);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
s.Append(b.ToString("x2").ToLower());
return s.ToString();
=== Aplicación en background ===
class Server {
public void Start() {
lock (this) {
// Hacer algo
Monitor.Wait(this);
}
}
public void Stop()
{
lock (this)
{
// Hacer algo
Monitor.PulseAll(this);
}
}
static void Main(string[] args) {
new Server().Start();
}
}
===== Trabajar con fuentes de datos =====
==== Tipo, nombre y número de campos ====
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Column Name:\t{0} {1}", reader.GetName(0).PadRight(25), reader.GetName(1));
Console.WriteLine("Data Type:\t{0} {1}", reader.GetDataTypeName(0).PadRight(25), reader.GetDataTypeName(1));
Console.WriteLine("Number of columns in a row: {0}", reader.FieldCount);
Console.WriteLine("'{0}' is at index {1} and its type is: {2}", reader.GetName(0), reader.GetOrdinal("FirstName"), reader.GetFieldType(0));
Console.WriteLine("'{0}' is at index {1} and its type is: {2}", reader.GetName(1), reader.GetOrdinal("LastName"), reader.GetFieldType(1));
reader.Close();
conn.Close();
==== Acceder a una DB Access ====
Access, al ser datos OLEDB, necesitamos objetos de ''System.Data.OleDb''.
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\prueba.mdb\"");
con.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("select * from Tabla1;", con);
System.Data.OleDb.OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Console.WriteLine("Id: {0} Nombre: {1}", reader["id"], reader["nombre"]);
con.Close();