C#从FTP下载/读取日志文件

时间:2019-02-13 09:36:24

标签: c# ftp ftpwebrequest

我在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()函数则输出了一个空内容。我找不到原因,有什么帮助吗?
注意:文件确实存在于服务器上,我可以列出它们。

1 个答案:

答案 0 :(得分:1)

根据MSDN,您的URL String myUrl = String.Format("ftp://{0}/{1}", IpAddress, infile);似乎是相对的,并且找不到要下载的文件。尝试检查服务器上文件的路径