Tag Archives: C#

Remove duplicated whitespaces on C#

The Trim method on C# only removes whitespaces at the beginning and at the end of a string, but it does not remote duplicated whitespaces inside the string (like the Trim function on VB for Apps), which is very handy sometimes.

One of the ways to do it on C#, is using Regular Expressions. This method will not only remove whitespaces but also tabs and line breaks, and will replace them with one whitespace.

string s1 = "He saw   a cute\tdog.\nThere\n\twas another sentence.";
Regex r = new Regex(@"\s+");
string s2 = r.Replace(s1, @" ");
// The result would be: He saw a cute dog. There was another sentence.

You will need to add the reference to System.Text.RegularExpressions to your namespace.
Source: Dot Net Perls

Convert a String to a Stream

In C#, to convert a String into a Stream object, we need to use the GetBytes method (from the Encoding.ASCII package), this way:

byte[] bytes = Encoding.ASCII.GetBytes(xmlContent);

And then, use that byte array when instantiate a Stream (for example, MemoryStream or FileStream):

MemoryStream stream = new MemoryStream(bytes);

Convertir un IList en un Array

Existen algunas formas de hacerlo, acá les dejo un par.

Primera forma:

//list es del tipo IList
ArrayList arr = new ArrayList(list);
Item[] items = (Item[])arr.ToArray(typeof(Item));

Otra forma:

Item[] items = new Item[list.Count];
list.CopyTo(items, 0);

Diferencia entre ICollection e IList en C#

Los elementos dentro de un ICollection (para ser más exactos, los elementos dentro de una clase que implemente una interfaz ICollection) no tienen un orden específico. En un momento pueden estar ordenados de una manera, y en otro, sin alguna razón aparente, ordenados de otra forma.

En cambio, los elementos de un IList si tienen un orden establecido y relevante, como un arreglo. Esto permite agregar elementos en una ubicación específica. Además, los elementos van a permanecer en la posición asignada hasta que decidamos moverlos.

Además de estas dos interfaces, existe también IDictionary, que exitiende a ICollection. Este permite almacenar parejas de elementos (clave, valor), similar a como lo hace un diccionario de palabras (cada palabra tiene un significado). Al igual que en el ICollection, estos elementos no tienen un orden específico.

Obtener el MimeType de un archivo desde C#

No he encontrado una manera directa de hacerlo, pero encontré esta función que busca la extensión del archivo en el registro de windows y si está registrada, obtiene su tipo mime.

private string getMimeType(string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
        mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}

Aún no la pruebo, pero según loque leí, funciona bien. Los post originales están acá y acá.