当前位置: 代码迷 >> C# >> 关于FTP指定目录的有关问题(C#)
  详细解决方案

关于FTP指定目录的有关问题(C#)

热度:95   发布时间:2016-05-05 03:54:50.0
关于FTP指定目录的问题(C#)
我用C#访问ftp的时候,他有一个默认路径,我现在要做的是访问他的根目录下的其他目录,例如下面:进入
ftp://123.12.12.12 进来后他默认的路径是ftp://123.12.12.12/aaa/bbb
我要访问ftp://123.12.12.12/ccc/ddd这个目录,怎么用程序控制,让我可以切换目录,在网上看到一些ftp的操作类,没有我需要的,求各位大神们给个方法啊,急急急急!!!!!!!!!!!
------解决思路----------------------

你直接把
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://123.12.12.12/aaa/bbb"));
------解决思路----------------------
private void DownloadImages(string localFolder, string remotPath, string fileName)
        {
            FtpWebRequest reqFTP;

            string ftpServerIP = ConfigurationManager.AppSettings["FtpServer"];
            string ftpUserID = ConfigurationManager.AppSettings["FtpUid"];
            string ftpPassword = ConfigurationManager.AppSettings["FtpPwd"];
            string ftpPort = ConfigurationManager.AppSettings["FtpPort"];

            try
            {
                FileStream outputStream = new FileStream(localFolder + "\\" + fileName, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + ":" + ftpPort + "/" + remotPath + "/" + fileName));

                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;

                reqFTP.UseBinary = true;

                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);

                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);

                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();

                outputStream.Close();

                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

//ftpServerIP 、ftpUserID 、ftpPassword、ftpPort  这些配置都写在App.config文件里
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="FtpServer" value="192.168.1.11"/>
    <add key="FtpUid" value="orms"/>
    <add key="FtpPwd" value="orms"/>
    <add key="FtpPort" value="22"/>
  </appSettings>
</configuration>

调用方法示例:

DownloadImages(@"d:\temp", "ccc/ddd", "test.jpg");

  相关解决方案