Wednesday, November 6, 2013

FTP over explict TLS c#

  protected void Button1_Click(object sender, EventArgs e)
    {
        RemoteCertificateValidationCallback orgCallback = ServicePointManager.ServerCertificateValidationCallback;
        try
        {
            // This statement is to ignore certification validation warning
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidateCertificate);
            ServicePointManager.Expect100Continue = true;
            // Connect to the server and do what ever you want here
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://72.167.40.137/NP/test.txt");
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.EnableSsl = true;
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("MSFMGR_USR", "Mtoli@_8228");
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] fileContents = encoding.GetBytes("Test file");
            // sourceStream.Close();
            request.ContentLength = fileContents.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            // Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
            response.Close();
        }
        finally
        {
            ServicePointManager.ServerCertificateValidationCallback = orgCallback;
        }
    }
   
    private bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

Monday, November 4, 2013