quarta-feira, 21 de julho de 2010

Listando arquivos de um diretório especificado

DirectoryInfo dir = new DirectoryInfo("C:\\");
FileInfo[] arquivos = dir.GetFiles("*.*");
foreach (FileInfo arquivo in arquivos)
    Console.Write(arquivo.Name);

Listando sub-diretórios de um diretório especificado

DirectoryInfo dir = new DirectoryInfo("C:\\");
DirectoryInfo[] diretorios = dir.GetDirectories();
foreach (DirectoryInfo diretorio in diretorios)
   Console.Write(diretorio.Name);

Listando drivers disponíveis

string[] drives = Directory.GetLogicalDrives();
foreach (string drive in drives)
      Console.Write(drive);

Reduzindo o tamanho de uma imagem

Fonte:
http://social.msdn.microsoft.com/Forums/pt-BR/aspnetpt/thread/0bb016f3-9260-489e-b5b0-0b44df66dfa7

Obs.:
Adaptado por Marcos Guedes (Programação Brasil).


Como utilizar:
TrataImagem objImg = new TrataImagem();
// Reduz o tamanho da imagem com 25% de qualidade
objImg.reduzir("c:\\caminhoImagemOrigem.png", "c:\\caminhoImagemDestino25.jpg", 25);

// Reduz o tamanho da imagem com 50% de qualidade
objImg.reduzir("c:\\caminhoImagemOrigem.png", "c:\\caminhoImagemDestino50.jpg", 50);

// Reduz o tamanho da imagem com 100% de qualidade
objImg.reduzir("c:\\caminhoImagemOrigem.png", "c:\\caminhoImagemDestino100.jpg", 100);



Código da Classe:
using System;
using System.Drawing;
using System.Drawing.Imaging;

class TrataImagem
{
    public void reduzir(string caminhoArquivoOriginal, string caminhoArquivoDestino, long qualidade)
    {
        Bitmap myBitmap;
        ImageCodecInfo myImageCodecInfo;
        Encoder myEncoder;
        EncoderParameter myEncoderParameter;
        EncoderParameters myEncoderParameters;

        // Create a Bitmap object based on a BMP file.
        myBitmap = new Bitmap(caminhoArquivoOriginal);

        // Get an ImageCodecInfo object that represents the JPEG codec.
        myImageCodecInfo = GetEncoderInfo("image/jpeg");

        // Create an Encoder object based on the GUID

        // for the Quality parameter category.
        myEncoder = Encoder.Quality;

        // EncoderParameter object in the array.
        myEncoderParameters = new EncoderParameters(1);

        // Save the bitmap as a JPEG file with quality level 25.            
        myEncoderParameter = new EncoderParameter(myEncoder, qualidade);
        myEncoderParameters.Param[0] = myEncoderParameter;
        myBitmap.Save(caminhoArquivoDestino, myImageCodecInfo, myEncoderParameters);
    }

    private static ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }
        return null;
    }
}

Excluindo um diretório e todo o seu conteúdo

string caminho = @"C:\seuDiretorio";
DirectoryInfo diretorio = new DirectoryInfo(caminho);
diretorio.Delete(true);

ProperCase

public string properCase(string entrada)
{
    entrada = entrada.ToLower();
    string sProper = "";

    char[] seps = new char[] { ' ' };
    foreach (string ss in entrada.Split(seps))
    {
        sProper += char.ToUpper(ss[0]);
        sProper +=
        (ss.Substring(1, ss.Length - 1) + ' ');
    }
    return sProper;
}
Fonte:
http://java2s.com/Code/CSharp/Data-Types/Showstringinpropercase.htm

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;
}

Enviando Email

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net;
using System.Net.Mail;

///
/// Summary description for EnviaEmail
///

namespace EnvioEmail
{
    public class EnviaEmail
    {
        #region valores padrões
        private string host = "smtp.gmail.com";
        private int porta = 587;
        private bool SSL = true;
        //
        private string nomeRemetente = "Nome do Remetente";
        private string emailRemetente = "email@remetente.com";
        private string nomeDestinatario = "Nome do Destinatário";
        private string emailDestinatario = "email@destinatario.com.br";
        //
        private bool isHTML = false;
        private string conteudo = "";
        private string assunto = "";
        //
        private string emailCredenciado = "teste@dominio.com";
        private string senhaCredenciada = "senha";
        #endregion

        #region métodos set para alteração dos valores padrões
        public void setHost(string host) { this.host = host; }
        public void setPorta(int porta) { this.porta = porta; }
        public void setSSL(bool SSL) { this.SSL = SSL; }
        public void setNomeRemetente(string nome) { this.nomeRemetente = nome; }
        public void setEmailRemetente(string email) { this.emailRemetente = email; }
        public void setNomeDestinatario(string nome) { this.nomeDestinatario = nome; }
        public void setEmailDestinatario(string email) { this.emailDestinatario = email; }
        public void setIsHTML(bool HTML) { this.isHTML = HTML; }
        public void setConteudo(string conteudo) { this.conteudo = conteudo; }
        public void setAssunto(string assunto) { this.assunto = assunto; }
        public void setEmailCrendeciado(string email) { this.emailCredenciado = email; }
        public void setSenhaCredenciada(string senha) { this.senhaCredenciada = senha; }
        #endregion

        public EnviaEmail()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public bool enviar()
        {
            // Enviar o email
            bool enviado = false;
            try
            {
                SmtpClient cliente = new SmtpClient(this.host, this.porta);
                cliente.EnableSsl = this.SSL; ;

                MailAddress remetente = new MailAddress(this.emailRemetente, this.nomeRemetente);
                MailAddress destinatario = new MailAddress(this.emailDestinatario, this.nomeDestinatario);
                MailMessage mensagem = new MailMessage(remetente, destinatario);
                mensagem.IsBodyHtml = this.isHTML; // define se será em formato html, ou não
                mensagem.Body = this.conteudo;
                mensagem.Subject = this.assunto;

                NetworkCredential credenciais = new NetworkCredential(this.emailCredenciado, this.senhaCredenciada, "");
                cliente.Credentials = credenciais;
                //
                cliente.Send(mensagem);
                enviado = true;
            }
            catch { }

            return enviado;
        }

        public bool enviar2()
        {
            // Use esta, se a função acima não funcionar
            bool enviado = false;
            try
            {
                SmtpClient cliente = new SmtpClient(this.host);
                NetworkCredential credenciais = new NetworkCredential(this.emailCredenciado, this.senhaCredenciada);
                //
                cliente.EnableSsl = this.SSL; ;
                cliente.UseDefaultCredentials = false;
                cliente.Credentials = credenciais;
                //
                MailAddress remetente = new MailAddress(this.emailRemetente);
                MailAddress destinatario = new MailAddress(this.emailDestinatario);
                MailMessage mensagem = new MailMessage(remetente, destinatario);
                //
                mensagem.IsBodyHtml = this.isHTML; // define se será em formato html, ou não
                mensagem.Body = this.conteudo;
                mensagem.BodyEncoding = System.Text.Encoding.UTF8;
                mensagem.Subject = this.assunto;
                mensagem.SubjectEncoding = System.Text.Encoding.UTF8;                
                //
                cliente.Send(mensagem);
                enviado = true;
            }
            catch { }

            return enviado;
        }
    }
}

FTP

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;

public class AcessoFTP
{
    #region Varáveis privadas
    private string addressFTP;
    private string userFTP;
    private string passwordFTP;
    private string filePathFTP;
    private string filePathLocal;
    private string msgStatus;

    private bool modoPassivo = true;

    private List listaFTP;
    private DataTable tbListaFTP;
    #endregion

    #region Variáveis públicas
    /// Endereço FTP
    public string ftpEndereco
    {
        get { return this.addressFTP; }
        set { this.addressFTP = value; }
    }
    /// Usuário FTP
    public string ftpUsuario
    {
        get { return this.userFTP; }
        set { this.userFTP = value; }
    }
    /// Senha FTP
    public string ftpSenha
    {
        get { return this.passwordFTP; }
        set { this.passwordFTP = value; }
    }
    ///
    /// Upload: Caminho do arquivo que será armazenado no servidor.
    /// Download: Caminho onde o arquivo será armazenado quando baixado do servidor FTP.
    ///
    public string ftpCaminhoArquivoLocal
    {
        get { return this.filePathLocal; }
        set { this.filePathLocal = value; }
    }
    ///
    /// Upload: Nome com o qual o arquivo que será armazenado no servidor.
    /// Download: Nome do arquivo que será baixado do servidor.
    ///
    public string ftpArquivoFTP
    {
        get { return this.filePathFTP; }
        set { this.filePathFTP = value; }
    }
    /// Status da última operação
    public string mensagemStatus
    {
        get { return this.msgStatus; }
    }

    ///
    /// True -> Modo Passivo; False -> Modo Ativo
    ///
    public bool ftpModoPassivo
    {
        set { this.modoPassivo = value; }
    }

    /// Armazena numa lista, o conteúdo do diretório filtrado.
    public List ftpDiretorioFTP
    {
        get { return this.listaFTP; }
    }
    /// Armazena num DataTable, o conteúdo do diretório filtrado.
    public DataTable ftpTbListaFTP
    {
        get { return this.tbListaFTP; }
    }
    #endregion

    #region Métodos que compõem a rotina
    /// Realiza upload de arquivos via FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpUpload()
    {
        bool sucesso;
        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/nomeArquivo.ext
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);
            //Cria uma solicitação FTP
            FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(caminho);

            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpRequest.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            ftpRequest.UsePassive = this.modoPassivo;
            ftpRequest.UseBinary = true;
            ftpRequest.KeepAlive = false;

            //Carrega o arquivo que será enviado para o servidor FTP
            FileStream arquivo = File.OpenRead(this.filePathLocal);
            byte[] buffer = new byte[arquivo.Length];

            arquivo.Read(buffer, 0, buffer.Length);
            arquivo.Close();

            //Upload file
            Stream reqStream = ftpRequest.GetRequestStream();
            reqStream.Write(buffer, 0, buffer.Length);
            reqStream.Close();

            this.msgStatus = "";
            sucesso = true;
        }
        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }
        return sucesso;
    }

    /// Realiza download de arquivos via FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpDownload()
    {
        bool sucesso;
        byte[] downloadedData = new byte[0];

        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/arquivo.txt
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);

            //Cria uma solicitação FTP
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(caminho);

            //Now get the actual data
            request = (FtpWebRequest)FtpWebRequest.Create(caminho);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            request.UsePassive = this.modoPassivo;
            request.UseBinary = true;
            request.KeepAlive = false; // Fechar a conexão quando concluído

            FtpWebResponse response = request.GetResponse() as FtpWebResponse;
            Stream reader = response.GetResponseStream();

            // Transfere para a memória
            // Nota: ajustar os fluxos aqui para fazer o download diretamente para o disco rígido
            MemoryStream memStream = new MemoryStream();
            byte[] buffer = new byte[1024]; //downloads in chuncks

            while (true)
            {
                // Tenta ler os dados
                int bytesRead = reader.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    break;
                }
                else
                {
                    //Escreve o conteúdo baixado
                    memStream.Write(buffer, 0, bytesRead);
                }
            }

            // Converter o fluxo baixado para um array de bytes
            downloadedData = memStream.ToArray();

            reader.Close();
            memStream.Close();
            response.Close();

            // Escreve os bytes do arquivo
            FileStream newFile = new FileStream(this.filePathLocal, FileMode.Create);
            newFile.Write(downloadedData, 0, downloadedData.Length);
            newFile.Close();

            sucesso = true;
        }
        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }

        return sucesso;
    }

    /// Preenche uma lista e DataTable com os dados do diretório FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpListarDiretorios()
    {
        List files = new List();
        bool sucesso;
        string conteudo;

        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/pastaDestino
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);

            //Cria uma solicitação FTP
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(caminho);

            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            request.UsePassive = this.modoPassivo;
            request.UseBinary = true;
            request.KeepAlive = false;

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);

            this.tbListaFTP = new DataTable();
            this.tbListaFTP.Columns.Add("Descrição", typeof(string));
            this.tbListaFTP.Columns.Add("Caminho", typeof(string));

            while (!reader.EndOfStream)
            {
                conteudo = reader.ReadLine();

                this.tbListaFTP.Rows.Add(conteudo, conteudo);
                files.Add(conteudo);
            }

            reader.Close();
            responseStream.Close();
            response.Close();

            this.msgStatus = "";
            sucesso = true;
        }

        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }

        this.listaFTP = files;

        return sucesso;
    }

    /// Preenche uma lista e DataTable com os dados do diretório FTP
    /// Extensão dos arquivos (*.ext)
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpListarDiretorios(string extensao)
    {
        List files = new List();
        bool sucesso;
        string conteudo;

        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/pastaDestino
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);

            //Cria uma solicitação FTP
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(caminho);

            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            request.UsePassive = this.modoPassivo;
            request.UseBinary = true;
            request.KeepAlive = false;

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);

            this.tbListaFTP = new DataTable();
            this.tbListaFTP.Columns.Add("Descrição", typeof(string));
            this.tbListaFTP.Columns.Add("Caminho", typeof(string));

            while (!reader.EndOfStream)
            {
                conteudo = reader.ReadLine();
                // Se a extensão for a exigida.
                if (Path.GetExtension(conteudo).ToUpper() == extensao.ToUpper())
                {
                    this.tbListaFTP.Rows.Add(conteudo, conteudo);
                    files.Add(conteudo);
                }
            }

            reader.Close();
            responseStream.Close();
            response.Close();

            this.msgStatus = "";
            sucesso = true;
        }

        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }

        this.listaFTP = files;

        return sucesso;
    }

    /// Deleta um arquivo de um diretório FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpDeletarArquivo()
    {
        bool sucesso;
        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/nomeArquivo.ext
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);
            //Cria uma solicitação FTP
            FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(caminho);

            ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
            ftpRequest.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            ftpRequest.UsePassive = this.modoPassivo;
            ftpRequest.UseBinary = true;
            ftpRequest.KeepAlive = false;

            // Deleta o arquivo
            FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
            response.Close();

            this.msgStatus = "";
            sucesso = true;
        }
        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }
        return sucesso;
    }
    #endregion
}

Lendo uma descrição de uma determinada linha num DataTable

string descricao;
int qualLinha = 0; // Primeira Linha
int qualColuna = 0; // Primeira Coluna

descricao = oDataTable.Rows[qualLinha].ItemArray.GetValue(qualColuna).ToString();

Abrindo a janela de salvar de arquivos

SaveFileDialog salvar = new SaveFileDialog();
//Tipo de arquivos que serão salvos
salvar.Filter = "Todos (*.*)|*.*|Texto (*.txt)|*.txt";
salvar.ShowDialog();

Abrindo a janela de seleção de arquivos

OpenFileDialog arquivo = new OpenFileDialog();
// Tipo de arquivos que serão filtrados
arquivo.Filter = "Todos (*.*)|*.*|Texto (*.txt)|*.txt"; 
arquivo.ShowDialog();

Obtendo Dados do Browser

ActiveXControls
Request.Browser.ActiveXControls

AOL
Request.Browser.AOL

BackgroundSounds
Request.Browser.BackgroundSounds

Beta
Request.Browser.Beta

Browser
Request.Browser.Browser

CDF
Request.Browser.CDF

ClrVersion
Request.Browser.ClrVersion

Cookies
Request.Browser.Cookies

Crawler
Request.Browser.Crawler

EcmaScriptVersion
Request.Browser.EcmaScriptVersion

Frames
Request.Browser.Frames

JavaApplets
Request.Browser.JavaApplets

JavaScript
Request.Browser.JavaScript

MajorVersion
Request.Browser.MajorVersion

MinorVersion
Request.Browser.MinorVersion

MSDomVersion
Request.Browser.MSDomVersion

Platform
Request.Browser.Platform

Tables
Request.Browser.Tables

Type
Request.Browser.Type

VBScript
Request.Browser.VBScript

Version
Request.Browser.Version

W3CDomVersion
Request.Browser.W3CDomVersion

Win16
Request.Browser.Win16

Win32
Request.Browser.Win32