本文整理汇总了C#中System.Net.FtpWebResponse.GetResponseStream方法的典型用法代码示例。如果您正苦于以下问题:C# FtpWebResponse.GetResponseStream方法的具体用法?C# FtpWebResponse.GetResponseStream怎么用?C# FtpWebResponse.GetResponseStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.FtpWebResponse
的用法示例。
在下文中一共展示了FtpWebResponse.GetResponseStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DownloadFtp
/// <summary>
/// 连接FTP的方法
/// </summary>
/// <param name="ftpuri">ftp服务器地址,端口</param>
/// <param name="ftpUserID">用户名</param>
/// <param name="ftpPassword">密码</param>
public DownloadFtp(string ftpuri, string ftpUserID, string ftpPassword)
{
// 根据uri创建FtpWebRequest对象
ft = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpuri));
// ftp用户名和密码
ft.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ft.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
fr = (FtpWebResponse)ft.GetResponse();
stream = fr.GetResponseStream();
////二进制文件读入
//if (!fr.ContentType.ToLower().StartsWith("text/"))
//{
// SaveBinaryFile(fr);
//}
////文本文件
//else
//{
string buffer = "", line;
StreamReader reader = new StreamReader(stream);
while ((line = reader.ReadLine()) != null)
{
buffer += line + "\r\n";
}
//装入整个文件之后,接着就要把它保存为文本文件。
SaveTextFile(buffer);
//}
}
示例2: DownloadFile
public void DownloadFile(string remoteFile, string localFile)
{
// Создаем FTP Request
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, remoteFile));
// Инициализируем сетевые учетные данные
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
// Задаем команду, которая будет отправлена на FTP-сервер
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.Timeout = TIMEOUT;
// Ответ FTP-сервера
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
// Возвращаем поток данных
ftpStream = ftpResponse.GetResponseStream();
// Создаем локальный файл
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
// Пишем в файл
ftpStream.CopyTo(localFileStream);
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
示例3: ListDirectory
public string[] ListDirectory(string directory)
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, directory));
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpRequest.Timeout = TIMEOUT;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
StreamReader ftpReader = new StreamReader(ftpStream);
string directoryRaw = null;
try
{
while (ftpReader.Peek() != -1)
{
//TODO: выдергиваем имя файла, доделать...
directoryRaw += ftpReader.ReadLine().Split(' ').Last() + "|";
}
}
catch
{
}
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
try
{
string[] directoryList = directoryRaw.Split("|".ToCharArray());
return directoryList;
}
catch
{
}
return new string[] { };
}
示例4: SaveBinaryFile
//二进制文件存储方法
protected void SaveBinaryFile(FtpWebResponse response)
{
byte[] buffer = new byte[1024];
string filename = convertFilename(response.ResponseUri);
Stream outStream = File.Create(filename);
Stream inStream = response.GetResponseStream();
int l;
do
{
l = inStream.Read(buffer, 0,
buffer.Length);
if (l > 0)
outStream.Write(buffer, 0, l);
} while (l > 0);
outStream.Close();
}
示例5: Download
/// <summary>
/// 下載FTP檔案
/// 存儲至Client端桌面
/// </summary>
/// <param name="FileName">要下載的檔案名稱</param>
/// <returns></returns>
public static bool Download(string FileName)
{
bool result = false;
string LocalFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" + FileName;
try
{
Uri FtpPath = new Uri(uriServer + FileName);
ftpRequest = (FtpWebRequest)WebRequest.Create(FtpPath);
ftpRequest.Credentials = new NetworkCredential(UserName,Password);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
ftpFileStream = new FileStream(LocalFile, FileMode.Create);
int BufferSize = 2048;
byte[] byteBuffer = new byte[BufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
try
{
while (bytesRead > 0)
{
ftpFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
}
result = true;
}
catch (Exception ex)
{
sysMessage.SystemEx(ex.Message);
}
ftpFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex)
{
sysMessage.SystemEx(ex.Message);
}
return result;
}
示例6: download
/* Download File */
public void download(string remoteFile, string localFile)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Get the FTP Server's Response Stream */
ftpStream = ftpResponse.GetResponseStream();
/* Open a File Stream to Write the Downloaded File */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
/* Download the File by Writing the Buffered Data Until the Transfer is Complete */
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
示例7: listFiles
//Sorts the files and only shows the files you want.
public List<String> listFiles(FtpWebResponse files, Boolean showAllFiles)
{
Stream responseStream = files.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
String filesFolders = reader.ReadToEnd();
List<String> fileArray = filesFolders.Split('\n').ToList<String>();
List<String> newList = new List<string>();
if (!showAllFiles)
{
foreach (String s in fileArray)
{
if (s.Contains(".mp3") || s.StartsWith("d")) //Feel free to add the filetypes you like.
{
if (s.Length > 0)
{
Char[] c = s.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == ':')
{
newList.Add(s.Substring(i + 4));
}
}
}
}
}
}
else
{
foreach (String s in fileArray)
{
newList.Add(s); //Adds all directorydetails
}
}
newList.Sort();
return newList;
}
示例8: DescargaArchivo
public string DescargaArchivo(string ArchivoFTP, string ArchivoLocal)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Direccion + "/" + ArchivoFTP);
ftpRequest.Credentials = new NetworkCredential(Usuario, Password);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
Console.WriteLine("Iniciando proceso de Descarga de Archivo.");
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream ArchivoDescargado = new FileStream(ArchivoLocal, FileMode.Create);
byte[] byteBuffer = new byte[2048];
int bytesRead = ftpStream.Read(byteBuffer, 0, 2048);
while (bytesRead > 0)
{
ArchivoDescargado.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, 2048);
}
Console.WriteLine("Proceso de Descarga Finalizado.");
EliminarArchivo(ArchivoFTP);
ArchivoDescargado.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
return "Exito";
}
catch (Exception)
{
Console.WriteLine("No se encuentra el archivo para descargar");
return "Error";
}
}
示例9: DownloadFileFTP
public bool DownloadFileFTP(string destinfilepath, string ftphost, string ftpfilepath, string user, string pass)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftphost + "//" + ftpfilepath);
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(destinfilepath, FileMode.Create);
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
return true;
}
catch (Exception erro)
{
throw new Exception(erro.Message);
}
}
示例10: worker_DoWork
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(data.adress + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(data.login, data.password);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Get the FTP Server's Response Stream */
ftpStream = ftpResponse.GetResponseStream();
/* Open a File Stream to Write the Downloaded File */
Directory.CreateDirectory(Path.GetDirectoryName(localFile));
localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
int totalBytesRead = bytesRead;
/* Download the File by Writing the Buffered Data Until the Transfer is Complete */
while (bytesRead > 0)
{
if (cancel)
{
localFileStream.Close();
ftpRequest.Abort();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
ftpResponse = null;
ftpStream = null;
localFileStream = null;
e.Cancel = true;
return;
}
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
totalBytesRead += bytesRead;
double progress = totalBytesRead * 100.0 / fileSize;
WorkerState state = new WorkerState(fileSize, totalBytesRead);
worker.ReportProgress((int)progress, state);
}
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
示例11: LoginCheck
// Anslutning till FTP - Server och listar innehållet
public bool LoginCheck()
{
try
{
// Skapa en FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host+":"+port);
// Loggar in på FTP Server med användarnman och lösenord
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
//Specificerar vilken typ av FTP Request
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
//Etablera Return kommunikation med FTP-servern
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
// Lagra FTP Serverns svarström
ftpStream = ftpResponse.GetResponseStream();
// Lagra FTP Serverns svarström
StreamReader ftpReader = new StreamReader(ftpStream);
// Lagrar responesen i variabeln directoryRaw
string directoryRaw = null;
// Läser rad för ar av svaret och lägger till en | för varje rad
try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
// Städar anslutningarna
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
try
{
string[] directoryList = directoryRaw.Split("|".ToCharArray());
Console.WriteLine("");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("========================================");
Console.ResetColor();
Console.WriteLine("Content of the FTP-Server");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("========================================");
Console.ResetColor();
foreach (var direct in directoryList)
{
Console.WriteLine(direct);
}
Console.WriteLine("");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("========================================");
Console.ResetColor();
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
catch (Exception)
{
return false;
}
return true;
}
示例12: lsSimple
private string[] lsSimple(string dir)
{
try
{
ftpRequest = (FtpWebRequest)WebRequest.Create(String.Format(baseUrl, dir));
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.EnableSsl = true;
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
StreamReader ftpReader = new StreamReader(ftpStream);
StringBuilder result = new StringBuilder();
try
{
string line = ftpReader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = ftpReader.ReadLine();
}
//remove extra \n
result.Remove(result.ToString().LastIndexOf('\n'), 1);
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
return result.ToString().Split('\n');
}
catch (Exception ex)
{
Console.WriteLine("Error reading file list.\n" + ex.ToString());
if (result != null)
result = null;
if (ftpReader != null)
ftpReader.Close();
if (ftpResponse != null)
ftpResponse.Close();
if (ftpRequest != null)
ftpRequest = null;
return new string[] { "" };
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return new string[] { "" };
}
示例13: download
public void download(string remoteFile, string localFile)
{
FileStream localFileStream = null;
try
{
ftpRequest = (FtpWebRequest)WebRequest.Create(String.Format(baseUrl, remoteFile));
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.UseBinary = false; //TODO: figure out why this downloads correctly when in most cases with windows it shouldn't
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.EnableSsl = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
localFileStream = new FileStream(localFile, FileMode.Create);
byte[] buffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(buffer, 0, bufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(buffer, 0, bufferSize);
bytesRead = ftpStream.Read(buffer, 0, bufferSize);
}
}
catch (Exception ex)
{
if (localFileStream != null)
localFileStream.Close();
Console.WriteLine("Error reading remote file.\n" + ex.ToString());
}
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch(Exception ex)
{
if (ftpRequest != null)
ftpRequest = null;
if (localFileStream != null)
localFileStream.Close();
if (ftpResponse != null)
ftpResponse.Close();
if (ftpStream != null)
ftpStream.Close();
Console.WriteLine("Error downloading file.\n" + ex.ToString());
}
}
示例14: DownloadFile
/*****************\
* Download file *
\*****************/
public void DownloadFile(string remoteFilePath, string localFilePath, double numberOfFiles, BackgroundWorker worker, DoWorkEventArgs e)
{
//List<object> parameters = e.Argument as List<object>;
List<object> returnArguments = new List<object>();
returnArguments.Add("Download");
try
{
//_DownloadedFileTarget = localFilePath;
_DownloadedFilesTarget.Add(localFilePath);
if (numberOfFiles == 1)
worker.ReportProgress(0);
/* Instanciate FTP request */
_FtpRequest = (FtpWebRequest)FtpWebRequest.Create(remoteFilePath);
/* Log in */
_FtpRequest.Credentials = new NetworkCredential(_User, _Password);
/* Set options */
_FtpRequest.UseBinary = true;
_FtpRequest.UsePassive = true;
_FtpRequest.KeepAlive = true;
/* Specify type of request */
_FtpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/* Establish return communication with ftp server */
_FtpResponse = (FtpWebResponse)_FtpRequest.GetResponse();
using (Stream ftpStream = _FtpResponse.GetResponseStream())
{
if (worker.CancellationPending)
{
e.Cancel = true;
}
else
{
/* Open a file stream to write the downloaded file */
FileStream localFileStream = new FileStream(localFilePath, FileMode.Create);
/* Buffer for the downloaded data */
byte[] byteBuffer = new byte[_BufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, _BufferSize);
/* Download the file by writting the buffered data until the transfer is complete */
try
{
double bytes = 0;
while (bytesRead > 0)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
bytes += bytesRead;
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, _BufferSize);
if (numberOfFiles == 1)
worker.ReportProgress(((int)(((bytes / 1000) / _TotalSize) * 100)));
}
}
catch (Exception ex) { returnArguments.Add(ex.ToString()); }
/* Ressources cleanup */
localFileStream.Close();
ftpStream.Close();
_FtpResponse.Close();
_FtpRequest = null;
}
}
}
catch (Exception ex) { returnArguments.Add(ex.ToString()); }
if(numberOfFiles == 1)
worker.ReportProgress(100);
e.Result = returnArguments;
}
示例15: ListDirectory
//Реализеум команду LIST для получения подробного списока файлов на FTP-сервере
public FileStruct[] ListDirectory(string path)
{
if (path == null || path == "")
{
path = "/";
}
//Создаем объект запроса
ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path);
//логин и пароль
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
//команда фтп LIST
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.EnableSsl = _UseSSL;
//Получаем входящий поток
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
//переменная для хранения всей полученной информации
string content = "";
StreamReader sr = new StreamReader(ftpResponse.GetResponseStream(), System.Text.Encoding.ASCII);
content = sr.ReadToEnd();
sr.Close();
ftpResponse.Close();
DirectoryListParser parser = new DirectoryListParser(content);
return parser.FullListing;
}