Using System;
Using System.IO;
Using System.Net;
Using System.Web.UI.WebControls;
Namespace ZC. Utils
{
public class Ftphelper
{
public string Upload (FileUpload FileUpload, String Ftpserverip, String Ftpuserid, String FTPPassword)
{
string filename = Fileupload.filename;
String Sret = "Upload succeeded!" ";
FileInfo Fileinf = new FileInfo (fileUpload.PostedFile.FileName);
String uri = "ftp://" + Ftpserverip + "/" + filename;
FtpWebRequest reqftp = (ftpwebrequest) webrequest.create (new Uri (URI));
Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);
Reqftp.keepalive = false;
Reqftp.method = "STOR";
Reqftp.usebinary = true;
Reqftp.usepassive = false;
Reqftp.contentlength = Fileinf.length;
int bufflength = 2048;
byte[] buff = new Byte[bufflength];
FileStream fs = Fileinf.openread ();
Try
{
Stream strm = Reqftp.getrequeststream ();
for (int contentlen = fs. Read (Buff, 0, bufflength); Contentlen! = 0; Contentlen = fs. Read (Buff, 0, bufflength))
{
Strm. Write (Buff, 0, Contentlen);
}
Strm. Close ();
Fs. Close ();
}
catch (Exception ex)
{
Sret = ex. Message;
}
return sret;
}
public string Download (string userId, string pwd, String Ftppath, String FilePath, String fileName)
{
string sret = "Download succeeded!" ";
Try
{
FileStream outputstream = new FileStream (FilePath + fileName, filemode.create);
FtpWebRequest reqftp = (ftpwebrequest) webrequest.create (new Uri (Ftppath + fileName));
Reqftp.method = "RETR";
Reqftp.usebinary = true;
Reqftp.usepassive = false;
Reqftp.credentials = new NetworkCredential (userId, PWD);
FtpWebResponse response = (ftpwebresponse) reqftp.getresponse ();
Stream FtpStream = Response. GetResponseStream ();
Long cl = Response. ContentLength;
int buffersize = 2048;
byte[] buffer = new Byte[buffersize];
for (int readcount = ftpstream.read (buffer, 0, buffersize); readcount > 0; readcount = ftpstream.read (buffer, 0, buffer Size))
{
Outputstream.write (buffer, 0, readcount);
}
Ftpstream.close ();
Outputstream.close ();
Response. Close ();
}
catch (Exception ex)
{
Sret = ex. Message;
}
return sret;
}
public string DeleteFile (string Ftppath, String userId, string pwd, String fileName)
{
String Sret = "Delete succeeded!" ";
FtpWebResponse respose = null;
Stream localfile = null;
Stream stream = null;
Try
{
FtpWebRequest reqftp = (ftpwebrequest) webrequest.create (The new Uri (string. Format ("{0}{1}", Ftppath, FileName));
Reqftp.credentials = new NetworkCredential (userId, PWD);
Reqftp.keepalive = false;
Reqftp.method = "DELE";
Respose = (ftpwebresponse) reqftp.getresponse ();
}
catch (Exception ex)
{
Sret = ex. Message;
}
Finally
{
if (respose! = null)
{
Respose.close ();
}
if (localfile! = null)
{
LocalFile. Close ();
}
if (stream! = null)
{
Stream. Close ();
}
}
return sret;
}
}
}
. NET uploading pictures across domains using FTP mode