quarta-feira, 21 de julho de 2010

Verificando conexão com a internet

Como chamar:
if (isConnectedDLL())
{
    // Com internet!
}
else
{
    // SEM internet!
}


A função:
using System.Runtime.InteropServices;

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
        
public bool isConnectedDLL()
{
    ///
    /// Fonte: http://social.msdn.microsoft.com/Forums/pt-BR/vscsharppt/thread/837efe78-19c3-4cd1-a4f9-93df16d16acb
    ///
    
    int desc;
    return InternetGetConnectedState(out desc, 0);            
}

Verifica se existe uma url está acessível

Como usar:
if (isConnectadURL())
{
    // URL acessível!
}
else
{
    // URL não acessível!
}

A função:
using System.Net;

public bool isConnectadURL()
{
    ///
    /// Fonte: http://www.portugal-a-programar.org/forum/index.php?topic=34048.0
    ///
    bool fail;

    System.Uri Url = new System.Uri("http://www.google.com"); //é sempre bom por um site que costuma estar sempre on, para n haver problemas

    WebRequest WebReq;
    WebResponse Resp;

    WebReq = WebRequest.Create(Url);

    try
    {
        Resp = WebReq.GetResponse();
        Resp.Close();
        WebReq = null;
        fail = true; //consegue conexão à internet                
    }

    catch
    {
        WebReq = null;
        fail = false; //falhou a conexão à internet                
    }            

    return fail;            
}


Nota: pode ser usado para verificar conexão com a internet

Utilizando a função ShellExecute

Como utilizar:
abrirURL("http://forum.programacaobrasil.com");
abrirURL("C:\\arquivo.doc");

A função:
using System.Runtime.InteropServices;

[DllImport("shell32.dll")]
private extern static int ShellExecute(int HWND, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

public int abrirURL(string url)
{
    ///
    /// Autor: Marcos Guedes
    /// Email: [Você precisa estar registrado e conectado para ver este link.]
    ///
    return ShellExecute(0, "open", url, "", "", 1);
}

Obtendo IP na internet

public string GetIpRemoto(string url)
{
    //Cria uma requisição para a URL
    WebRequest rq = WebRequest.Create(url);

    //obtém o response a partir do request
    HttpWebResponse rp = (HttpWebResponse)rq.GetResponse();
    //obtém um stream contendo a resposta retornada pelo servidor
    Stream ds = rp.GetResponseStream();
    //Cria um StreamReader para leitura
    StreamReader rd = new StreamReader(ds);
    //Lê os dados
    string responseFromServer = rd.ReadToEnd();
    //fecha os objetos
    rd.Close();
    ds.Close();
    rp.Close();
    //procura por indexafor fixo no resultado 
    string URL = "IP";
    int i = responseFromServer.IndexOf(URL) + URL.Length + 2;
    //captura o IP descoberto
    URL = string.Empty;
    while (!(responseFromServer[i].ToString() == "<"))
    {
        URL += responseFromServer[i];
        i += 1;
    }      

    return URL.Trim();
}

Lendo arquivos texto

Solução por Marcos Guedes (Programação Brasil):
public string lerArquivo(string caminhoArquivo)
{
  int counter = 0;
  string line;
  string conteudo = "";

  System.IO.StreamReader file = new System.IO.StreamReader(caminhoArquivo);
  while ((line = file.ReadLine()) != null)
  {
      conteudo += line +  (char)13 + (char)10 ;
      counter++;
  }

  file.Close();
  return conteudo;
}

Solução por Rubem Rocha (Programação Brasil) :

public string LerArquivoTexto(string nomeArquivo)
{
  if (File.Exists(nomeArquivo))
      return File.ReadAllText(nomeArquivo);
  else
      return String.Empty;
}

ou

public static string[] LerArquivoTexto(string nomeArquivo)
{
  if (!File.Exists(nomeArquivo)) return (new string[] {});
  string buffer = File.ReadAllText(nomeArquivo, Encoding.Default);
  return (buffer.Split(new string[] { "\r\n" }, StringSplitOptions.None));
}

Retira acentos de textos

public string TirarAcentos(string texto)
{
   string textor = "";
   
   for (int i = 0; i < texto.Length; i++)
   {
       if (texto[i].ToString() == "ã") textor += "a";
       else if (texto[i].ToString() == "á") textor += "a";
       else if (texto[i].ToString() == "à") textor += "a";
       else if (texto[i].ToString() == "â") textor += "a";
       else if (texto[i].ToString() == "ä") textor += "a";
       else if (texto[i].ToString() == "é") textor += "e";
       else if (texto[i].ToString() == "è") textor += "e";
       else if (texto[i].ToString() == "ê") textor += "e";
       else if (texto[i].ToString() == "ë") textor += "e";
       else if (texto[i].ToString() == "í") textor += "i";
       else if (texto[i].ToString() == "ì") textor += "i";
       else if (texto[i].ToString() == "ï") textor += "i";
       else if (texto[i].ToString() == "õ") textor += "o";
       else if (texto[i].ToString() == "ó") textor += "o";
       else if (texto[i].ToString() == "ò") textor += "o";
       else if (texto[i].ToString() == "ö") textor += "o";
       else if (texto[i].ToString() == "ú") textor += "u";
       else if (texto[i].ToString() == "ù") textor += "u";
       else if (texto[i].ToString() == "ü") textor += "u";
       else if (texto[i].ToString() == "ç") textor += "c";
       else if (texto[i].ToString() == "Ã") textor += "A";
       else if (texto[i].ToString() == "Á") textor += "A";
       else if (texto[i].ToString() == "À") textor += "A";
       else if (texto[i].ToString() == "Â") textor += "A";
       else if (texto[i].ToString() == "Ä") textor += "A";
       else if (texto[i].ToString() == "É") textor += "E";
       else if (texto[i].ToString() == "È") textor += "E";
       else if (texto[i].ToString() == "Ê") textor += "E";
       else if (texto[i].ToString() == "Ë") textor += "E";
       else if (texto[i].ToString() == "Í") textor += "I";
       else if (texto[i].ToString() == "Ì") textor += "I";
       else if (texto[i].ToString() == "Ï") textor += "I";
       else if (texto[i].ToString() == "Õ") textor += "O";
       else if (texto[i].ToString() == "Ó") textor += "O";
       else if (texto[i].ToString() == "Ò") textor += "O";
       else if (texto[i].ToString() == "Ö") textor += "O";
       else if (texto[i].ToString() == "Ú") textor += "U";
       else if (texto[i].ToString() == "Ù") textor += "U";
       else if (texto[i].ToString() == "Ü") textor += "U";
       else if (texto[i].ToString() == "Ç") textor += "C";
       else textor += texto[i];
   }
   return textor;
}

Retornando o conteúdo de uma página web

public string GetContent(string url)
{
    string result = "Error communicating with server";
    System.Net.HttpWebRequest wreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
    wreq.Method = "GET";
    wreq.Timeout = 3000;
    System.Net.HttpWebResponse wr = (System.Net.HttpWebResponse)wreq.GetResponse();

    if (wr.StatusCode == System.Net.HttpStatusCode.OK)
    {
        System.IO.Stream s = wr.GetResponseStream();
        System.Text.Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        System.IO.StreamReader readStream = new System.IO.StreamReader(s, enc);
        result = readStream.ReadToEnd();
    }
    return result;
}