Simple instance for downloading files to the FTP server
Code
String Filepath = " D :\\ " ;
String Filename = " Lhking.txt " ; // Path and file name to be saved after the file is downloaded
Ftpwebrequest reqftp;
Try
{
Filestream outputstream = New Filestream (filepath + " \\ " + Filename, filemode. Create );
String Filename = " Ip.txt " ;
String Ftpserverip = " 222.76.217.24 " ;
Reqftp = (Ftpwebrequest) ftpwebrequest. Create ( New Uri ( " FTP :// " + Ftpserverip + " / " + Filename ));
Reqftp. Method = Webrequestmethods. FTP. downloadfile;
Reqftp. usebinary = True ;
Reqftp. Credentials = New Networkcredential ( " L " , " L " );
Ftpwebresponse response = (Ftpwebresponse) reqftp. getresponse ();
Stream ftpstream = Response. getresponsestream ();
Long Cl = Response. contentlength;
Int Buffersize = 2048 ;
Int Readcount;
Byte [] Buffer = New Byte [Buffersize];
Readcount = Ftpstream. Read (buffer, 0 , Buffersize );
While (Readcount > 0 )
{
Outputstream. Write (buffer, 0 , Readcount );
Readcount = Ftpstream. Read (buffer, 0 , Buffersize );
}
Ftpstream. Close ();
Outputstream. Close ();
Response. Close ();
}
Catch (Exception ERR)
{
MessageBox. Show (ERR. Message, " Download Error " );
}
Simple Example of uploading files to the FTP server
Code
String Filename = " Ip.txt " ;
String Ftpserverip = " 222.76.217.24 " ;
Fileinfo fileinf = New Fileinfo (filename );
String Uri = " FTP :// " + Ftpserverip + " / " + Fileinf. Name;
Ftpwebrequest reqftp;
Reqftp = (Ftpwebrequest) ftpwebrequest. Create ( New Uri ( " FTP :// " + Ftpserverip + " / " + Fileinf. Name ));
Reqftp. Credentials = New Networkcredential ( " L " , " L " );
Reqftp. keepalive = False ;
Reqftp. Method = Webrequestmethods. FTP. uploadfile;
Reqftp. usebinary = True ;
Reqftp. contentlength = Fileinf. length;
Int Bufflength = 2048 ;
Byte [] Buff = New Byte [Bufflength];
Int Contentlen;
Filestream FS = Fileinf. openread ();
Try
{
Stream STRM = Reqftp. getrequeststream ();
Contentlen = FS. Read (buff, 0 , Bufflength );
While (Contentlen ! = 0 )
{
STRM. Write (buff, 0 , Contentlen );
Contentlen = FS. Read (buff, 0 , Bufflength );
}
STRM. Close ();
FS. Close ();
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message, " Upload Error " );
}
If you want to convert stream to a string, write it as follows.
Streamreader sr = new streamreader (ftpstream, encoding. Default );
String STR = Sr. readtoend ();