Today, i'll show you how to downloading a File with a Save As Dialog in ASP.NET. The complete code for this is shown blow.
private void Download(string FilePath)
{
FtpWebRequest reqFTP;
try
{
string FTPServer = ConfigurationManager.AppSettings.Get("FTPServer");
string User = ConfigurationManager.AppSettings.Get("User");
string Pwd = ConfigurationManager.AppSettings.Get("Pwd");
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPServer + FilePath));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(User, Pwd);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
string[] fileName = FilePath.Split(new char[] { '\\' });
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName[fileName.Length - 1].ToString());
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
Response.OutputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
// Log you error here
}
}
FTP File List
private void FileList(rstring FilePath)
{
string FTPServer = ConfigurationManager.AppSettings.Get("FTPServer");
string User = ConfigurationManager.AppSettings.Get("User");
string Pwd = ConfigurationManager.AppSettings.Get("Pwd");
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPServer + FilePath));
ftpWebRequest.Credentials = new NetworkCredential(User, Pwd);
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
using (StreamReader sReader = new StreamReader(ftpWebRequest.GetResponse().GetResponseStream()))
{
string str = sReader .ReadLine();
while (str != null)
{
Response.Write(str);
str = sReader.ReadLine();
}
}
ftpWebRequest = null;
}