private void UploadFiles()
{
try
{
string ftplocation = "ftp://ServerIp//Directory";
string file = @"InputFilePath";
string user = "username";
string password = "password";
String filename = Path.GetFileName(file);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftplocation + "/" + "UploadFileName");
// 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;
// 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