Skip to content

Instantly share code, notes, and snippets.

@RahulSharma
Last active June 26, 2020 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RahulSharma/4eb4e2c9cf9464e748a2ad876080f4a9 to your computer and use it in GitHub Desktop.
Save RahulSharma/4eb4e2c9cf9464e748a2ad876080f4a9 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace FTPLibrary
{
//DTO to hold required info for FTP call
public class ServiceInfo
{
private string userName;
private string password;
private string url;
private string fileName;
public string UserName { get => userName; set => userName = value; }
public string Password { get => password; set => password = value; }
public string Url { get => url; set => url = value; }
public string FileName { get => fileName; set => fileName = value; }
}
//This is main class that exposes FTP operations
public class Service
{
//This method takes string as file content and ServiceInfo object, to create/upload the file.
public static string Upload(string requestXML, ServiceInfo serviceInfo)
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serviceInfo.Url + serviceInfo.FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
//Credentials
request.Credentials = new NetworkCredential(serviceInfo.UserName , serviceInfo.Password);
// Copy the contents of the file to the request stream.
byte[] fileContents;
fileContents = Encoding.UTF8.GetBytes(requestXML);
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
string responseString;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
responseString = $"File uploaded- status {response.StatusDescription}";
}
return responseString;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment