Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anterior Revisión previa Próxima revisión | Revisión previa | ||
|
highlevel:csharp:snippets [2009/02/23 15:55] alfred |
highlevel:csharp:snippets [2020/05/09 09:25] (actual) |
||
|---|---|---|---|
| Línea 1: | Línea 1: | ||
| ====== C# code snippets ====== | ====== C# code snippets ====== | ||
| ===== Trabajo con datos ===== | ===== Trabajo con datos ===== | ||
| + | |||
| ==== Conversiones ==== | ==== Conversiones ==== | ||
| === De byte a String === | === De byte a String === | ||
| Línea 14: | Línea 15: | ||
| Encoding.UTF8.GetString(myByteArray)) | Encoding.UTF8.GetString(myByteArray)) | ||
| </code> | </code> | ||
| + | ==== 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 ==== | ==== Fechas ==== | ||
| Línea 26: | Línea 30: | ||
| System.Console.WriteLine("Difference in days: {0} ", differenceInDays); | System.Console.WriteLine("Difference in days: {0} ", differenceInDays); | ||
| </code> | </code> | ||
| + | |||
| + | |||
| Línea 49: | Línea 55: | ||
| <code csharp> | <code csharp> | ||
| StreamWriter sw = new StreamWriter(File.Open(sFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)); | StreamWriter sw = new StreamWriter(File.Open(sFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)); | ||
| + | </code> | ||
| + | |||
| + | === Escribir en UTF8 === | ||
| + | <code csharp> | ||
| + | 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(); | ||
| + | </code> | ||
| + | |||
| + | ==== XML ==== | ||
| + | Abrir archivos para lectura, con la referencia ''System.Xml'' agregada: | ||
| + | <code csharp> | ||
| + | XmlDocument doc = new XmlDocument(); | ||
| + | doc.Load(path); | ||
| + | </code> | ||
| + | Coger nodos por nombre: | ||
| + | <code chsarp> | ||
| + | XmlNode mainNode = doc.GetElementsByTagName("kvtml")[0]; | ||
| + | </code> | ||
| + | Coger nodos hijo: | ||
| + | <code csharp> | ||
| + | XmlNodeList nodes = mainNode.ChildNodes; | ||
| + | </code> | ||
| + | Coger texto interno: | ||
| + | <code csharp> | ||
| + | foreach (XmlNode node in nodes) | ||
| + | { | ||
| + | lang1 = node.ChildNodes[0].InnerText; | ||
| + | } | ||
| + | </code> | ||
| + | |||
| + | ==== Expresiones regulares ==== | ||
| + | === Eliminar las tags de un texto === | ||
| + | <code csharp> | ||
| + | using System.Text.RegularExpressions; | ||
| + | public string Strip(string text) | ||
| + | { | ||
| + | return Regex.Replace(text, @”<(.|\n)*?>”, string.Empty); | ||
| + | } | ||
| + | </code> | ||
| + | ==== Descargar archivos de internet ==== | ||
| + | <code csharp> | ||
| + | System.Net.WebClient wc = new System.Net.WebClient(); | ||
| + | wc.DownloadFile("http://url/imagen.jpg", "c:\\img.jpg"); | ||
| </code> | </code> | ||
| Línea 232: | Línea 284: | ||
| } | } | ||
| </code> | </code> | ||
| + | |||
| + | |||
| Línea 331: | Línea 385: | ||
| return buffer; | return buffer; | ||
| </code> | </code> | ||
| + | |||
| + | |||
| + | |||
| Línea 398: | Línea 455: | ||
| <code csharp> | <code csharp> | ||
| System.Drawing.Text.InstalledFontCollection | System.Drawing.Text.InstalledFontCollection | ||
| + | </code> | ||
| + | === Saber el usuario que está ejecutando el programa === | ||
| + | Dentro de ''System.Security.Principal'' ... | ||
| + | <code csharp> | ||
| + | WindowsIdentity id = WindowsIdentity.GetCurrent(); | ||
| + | id.name; | ||
| + | </code> | ||
| + | === Lanzar un comando y quedarte con su salida === | ||
| + | <code csharp> | ||
| + | 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; | ||
| + | } | ||
| + | </code> | ||
| + | === Encriptar en MD5 === | ||
| + | <code csharp> | ||
| + | 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); | ||
| + | } | ||
| + | </code> | ||
| + | ... o ... | ||
| + | <code csharp> | ||
| + | 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(); | ||
| + | </code> | ||
| + | |||
| + | === Aplicación en background === | ||
| + | <code csharp> | ||
| + | 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(); | ||
| + | } | ||
| + | } | ||
| </code> | </code> | ||
| Línea 416: | Línea 557: | ||
| conn.Close(); | conn.Close(); | ||
| </code> | </code> | ||
| + | |||
| + | |||
| + | |||
| ==== Acceder a una DB Access ==== | ==== Acceder a una DB Access ==== | ||
| + | Access, al ser datos OLEDB, necesitamos objetos de ''System.Data.OleDb''. | ||
| <code csharp> | <code csharp> | ||
| System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\prueba.mdb\""); | System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\prueba.mdb\""); | ||
| Línea 423: | Línea 568: | ||
| System.Data.OleDb.OleDbDataReader reader = cmd.ExecuteReader(); | System.Data.OleDb.OleDbDataReader reader = cmd.ExecuteReader(); | ||
| while (reader.Read()) | while (reader.Read()) | ||
| - | Console.WriteLine("Id: {0} Nombre: {1}", reader.GetInt32(reader.GetOrdinal("id")), reader.GetString(reader.GetOrdinal("nombre"))); | + | Console.WriteLine("Id: {0} Nombre: {1}", reader["id"], reader["nombre"]); |
| con.Close(); | con.Close(); | ||
| </code> | </code> | ||
| + | |||