在C#中怎样自动下载ftp中指定目录下的一个文件?
展开全部
public string Download(string filePath, string fileName)////上面的衡裂腔代码实现了从ftp服务器下载文件的功咐衫能
{
try
{
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + "源汪\\" + onlyFileName;
if (File.Exists(newFileName))
{
return "本地文件" + newFileName + "已存在,无法下载";
}
string url = "ftp://" + ftpServerIP + "/" + fileName;
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
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);
FileStream outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return "";
}
catch (Exception ex)
{
return "因"+ex.Message+",无法下载";
}
}
{
try
{
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + "源汪\\" + onlyFileName;
if (File.Exists(newFileName))
{
return "本地文件" + newFileName + "已存在,无法下载";
}
string url = "ftp://" + ftpServerIP + "/" + fileName;
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
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);
FileStream outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return "";
}
catch (Exception ex)
{
return "因"+ex.Message+",无法下载";
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询