我在FTP服务器上有几个.log
文件。我需要在我的驱动器上下载它们。或者,阅读和显示内容。我在这里阅读了相关的帖子,并提出了代码:
下载
public void DownloadFile(String infile)
{
String myUrl = String.Format("ftp://{0}/{1}", IpAddress, infile);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(myUrl));
request.Credentials = new NetworkCredential(UserName, Password);
request.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
String output = String.Format("{0}", infile);
using (StreamWriter destination = new StreamWriter(output))
{
destination.Write(reader.ReadToEnd());
destination.Flush();
}
reader.Close();
response.Close();
}
读
public string ReadTxtFile2(String infile)
{
WebClient request = new WebClient();
String url = String.Format("ftp://{0}/{1}", IpAddress, infile);
request.Credentials = new NetworkCredential(UserName, Password);
try
{
// also tried: String fileString = request.DownloadString(url);
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
return fileString;
}
catch (WebException e)
{
return e.Message;
}
}
不知何故,下载返回一个空的0 kb文件,read()函数输出一个空内容。我找不到原因,有什么帮助吗? 注意:服务器上存在文件,我可以列出它们。
根据MSDN您的URL String myUrl = String.Format("ftp://{0}/{1}", IpAddress, infile);
似乎是相对的,您的文件无法下载。尝试检查服务器上的文件路径