In the code below, we can see how files are transferred to an FTP server using X++.
Prerequisites :
FTP Address: The address used to connect to the FTP server.
Username: The authorized username required for logging into the FTP server.
Password: The password needed to access the FTP.
Folder paths: The locations of folders where files can be placed or read. public void sendFileToFTP(System.IO.Stream _stream)
{
System.Text.Encoding getUTF8;
System.Byte[] bytes;
System.Object request,response,credential;
System.Net.FtpWebRequest ftpRequest;
System.IO.Stream requestStream;
System.Net.FtpWebResponse ftpResponse;
System.IO.StreamReader reader;
System.Char[] chars;
Str1260 ftpFileName = "ftp://<Ipaddress>//INPUT/UNPROCESSED/ "+ filename ; // folder paths
try
{
_stream.Position = 0;
// Encode
reader = new System.IO.StreamReader(_stream);
getUTF8 = System.Text.Encoding::get_UTF8();
bytes = getUTF8.GetBytes(reader.ReadToEnd());
// Creating request
request = System.Net.WebRequest::Create(new System.Uri(ftpFileName));
ftpRequest = request;
// Creating credentials
credential = new System.Net.NetworkCredential('UserName', 'Password');
// assign parameters to reuest
ftpRequest.set_Credentials(credential);
ftpRequest.set_ContentLength(bytes.get_Length());
ftpRequest.set_Method("STOR");
// Write file to stream
requestStream = ftpRequest.GetRequestStream();
requestStream.Write(bytes,0,bytes.get_Length());
requestStream.Close();
// Get respose
response = ftpRequest.GetResponse();
ftpResponse = response;
info('Uploded.');
}
catch
{
error("failed");
}
}public static str readFileFromSFTP(FileName _fileName)
{
System.Object ftpo;
System.Net.FtpWebRequest request;
System.IO.StreamReader reader;
System.Net.NetworkCredential credential;
System.Net.FtpWebResponse response;
Str1260 text;
UserId usernameFTP;
Password password;
Str1260 readingPath;
try
{
ttsbegin;
password = cryptoblob2str(WinAPIServer::cryptUnProtectData('password'));
ftpo = System.Net.WebRequest::Create(@'FolderpathtoReadFie' + @"/" + _fileName);
request = ftpo;
credential = new System.Net.NetworkCredential('UserName', password);
request.set_Credentials(credential);
response = request.GetResponse();
reader = new System.IO.StreamReader(response.GetResponseStream());
text = reader.ReadToEnd();
ttscommit;
}
catch
{
error("Error reading files");
}
return text;
}Keep Daxing !!
No comments:
Post a Comment