Monday, February 27, 2023

Upload a file to FTP server using x++.

 Upload and read files from the FTP server using x++.

The file name should not contain spaces and a colon(":").


 Upload file:

static 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;
	Str1260 			ftpFileName = "FTP server" + @"/" + "filename.csv";
	System.IO.StreamReader 		reader;
	System.Char[] 			chars;
	
	/* If file to be created with current data and time we can use this commented code.
            str   timeinstr, executedate;
	    //removed spaces and colons because of FTP protocol voilation and throws error
	    timeinstr = strRem(time2str(timeNow(),DateSeparator::Dot,DateSeparator::Dot)," ");

	    //part of filename
	    executedate = date2Str(today(),213,
				DateDay::Digits2,
				DateSeparator::Hyphen,
			        DateMonth::Digits2,
				DateSeparator::Hyphen,
				DateYear::Digits4);

	    executedate = executedate + "_" + timeinstr + ".CSV";
        */
	
	//new InteropPermission(InteropKind::ClrInterop).assert();
	
	// Convert protect password to normal.
	//cryptoblob2str(WinAPIServer::cryptUnProtectData('Protected Password'))
	
	_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");
	ftpRequest.set_Proxy(null);
	
	// 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.');
}


Read file:

public static void ReadFileFromFTP(Str1260 _fileName)
{
    Str1260                         readingPath = 'FTP server';
    System.Object                   ftpRequest;
    System.Net.FtpWebRequest        request;
    System.IO.StreamReader          reader;
    System.Net.NetworkCredential    credential;
    System.Net.FtpWebResponse       response;

    try
    {
	// Convert protect password to normal.
	//cryptoblob2str(WinAPIServer::cryptUnProtectData('Protected Password'))

	// Create request
	ftpRequest      = System.Net.WebRequest::Create(@readingPath + @"/" + _fileName);
	request         = ftpRequest;

	credential      = new System.Net.NetworkCredential('username', 'password');
		
	request.set_Credentials(credential);
		
	response        = request.GetResponse();
	reader          = new System.IO.StreamReader(response.GetResponseStream());
		
	str 	text = reader.ReadToEnd();
    }
    catch
    {
	error("Error");
    }
}

Keep Daxing!!

No comments:

Post a Comment