My Simple Upload Program using FTPs (Net Core 2.0 and Visual Studio 2017 v15.3.5)

1. FTPS Server is built in IIS7
2. FtpWebRequest seems to work well in Net Core v2

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using FTPs.Models;
using System.Net;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;

namespace FTPs.Controllers
{
    public class HomeController : Controller
    {
        public X509Certificate2 FindCertificateFromStore(X509FindType findType, string findValue)
        {
              //W10: type certificate to search and select Manager User Certificates
              X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            // https://stackoverflow.com/questions/8448147/problems-with-x509store-certificates-find-findbythumbprint
            // The SerialNumber and ThumbPrint copied from MMC tools contains special chars
            // Please copy /paste all string value (includign quote symbol!) into Noetpad++ (not notepad) and re-edit it
            //string thumbprint = "F11DD97AC7DCE97F96992C880C4127E5EEEE6A26";
            //thumbprint = Regex.Replace(thumbprint, @"[^\da-zA-z]", string.Empty).ToUpper();
         
            X509Certificate2Collection foundCerts = store.Certificates.Find(findType, findValue, true);
            store.Close();
            return foundCerts.Count == 0 ? null : foundCerts[0];
        }
        public void UploadFile()
        {
            // https://github.com/hgupta9/FluentFTP

            StreamReader sourceStreamReader = null;
            Stream requestStream = null;
            FtpWebResponse response = null;

            try
            {
//                ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://server/subfolder/UploadedSample.txt");
                request.Credentials = new NetworkCredential("username", "password");
                request.UseBinary = false;
                request.UsePassive = true;
                request.EnableSsl = true;
                request.KeepAlive = false;

                //X509Certificate2 cert = FindCertificateFromStore(X509FindType.FindBySubjectName, "server");
                //http://www.codeguru.com/csharp/.net/net_security/authentication/article.php/c15051/ASPNET-FTP-with-SSL.htm

                //X509Certificate2 cert = new X509Certificate2("H:\\FTPs\\JackMyPubKey.cer");
                //if (cert != null)
                    //request.ClientCertificates.Add(cert);
             
                request.Method = WebRequestMethods.Ftp.UploadFile;
             
                sourceStreamReader = new StreamReader(@"c:\FTPs\sample.txt");
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStreamReader.ReadToEnd());
                sourceStreamReader.Close();
                request.ContentLength = fileContents.Length;

                requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                response = (FtpWebResponse)request.GetResponse();
                //Console.WriteLine("Congrats, Upload File Complete, status {0}", response.StatusDescription);
                ViewData["CompleteStatus"] = String.Format("Congrats! Upload complete: {0}", response.StatusDescription);
                response.Close();
            }
            catch (WebException e)
            {
                Console.WriteLine(e.Message.ToString());
                String status = ((FtpWebResponse)e.Response).StatusDescription;
                ViewData["ExceptionStatus"] = String.Format("Sorry, Upload WebException: {0}", status);
            }
            catch (Exception ex)
            {
                string status = ex.Message.ToString();
                ViewData["ExceptionStatus"] = String.Format("Sorry, Upload Exception: {0}", status);
            }
            finally
            {
                if (sourceStreamReader != null)
                    sourceStreamReader.Close();
                if (requestStream != null)
                    requestStream.Close();
                if (response != null)
                    response.Close();
            }
        }

        public IActionResult Index()
        {
            UploadFile();
            return View();
        }

    }
}

Comments

Popular posts from this blog

Use GnuPG Tools or C# Code for PGP Encryption and Signature

Errors in Net Core Add-Migration

Confusing Concepts about SFTP: SSH2 vs OpenSSH