In day to day life, we will come across various scenarios which requires file transfer from application to Web Server/Data Base server to have certian functionalities to achieve. So , i thought if code is available online it will be easy for the developers to write code in less time.
Here is the Code snippet for the FTP File Transfer:
///This method will copy files from Application Server Directory to a remote server using FTP.
private void UploadFiles()
{
try
{
string ftplocation = "ftp://TargetServerwithport//directorynameintargetserver/";
string file = @"D:\BaseFolder\Sample.txt";
//Provide the credentials to connect to Target FTP Server , good practice is store them in config files
string user = "test";
string password = "test123";
String filename = Path.GetFileName(file);
// Open a request using the full URI
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftplocation + "/" + "Sample.txt");
// Configure the connection request
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(user, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.Proxy = null;
request.Timeout = 600000; //Time out for request to be processed
// Create a stream from the file
FileStream stream = File.OpenRead(file);
byte[] buffer = new byte[stream.Length];
// Read the file into the a local stream
stream.Read(buffer, 0, buffer.Length);
// Close the local stream
stream.Close();
// Create a stream to the FTP server
Stream reqStream = request.GetRequestStream();
// Write the local stream to the FTP stream
// 2 bytes at a time
int offset = 0;
int chunk = (buffer.Length > 2048) ? 2048 : buffer.Length;
while (offset < buffer.Length)
{
reqStream.Write(buffer, offset, chunk);
offset += chunk;
chunk = (buffer.Length - offset < chunk) ? (buffer.Length - offset) : chunk;
}
// Close the stream to the FTP server
reqStream.Close();
}
catch (Exception ex)
{
//TODO: Exception handling
}
}
No comments:
Post a Comment