c#用Socket取得FTP服务器的根目录下面的文件夹

时间:2022-04-03 13:05:11
            string RemoteHost = @"ftp://xxxxx.jp";
            string UserName = "UserName ";            
            string Password = "Password ";              
            string RemotePath = "/";
            Uri myUri = new Uri(RemoteHost);
            string host = myUri.Host;
            IPHostEntry hostInfo = Dns.GetHostEntry(host);
            string ip = hostInfo.AddressList[0].ToString();
求大神给一段代码:
              第一步:怎么链接服务器。第二步:怎么取得根目录下面的文件夹。
不需要其他任何功能,代码越少越好。

1 个解决方案

#1


还是自己来吧!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FTPTest
{
    public partial class Form1 : Form
    {

        //ADD*******************************
        //変数の宣言
        public Socket socketControl;
        public int iReplyCode;
        public string strReply;
        string RemoteHost = @"ftp://xxxxxxx";
        string UserName = "xxxxxx"; 
        string Password = "xxxxxxx";    

        string RemotePath = "/";
        public string strMsg;
        Byte[] buffer = new Byte[5000];
        Encoding ASCII = Encoding.Default;
        public string ip;
        //ADD*******************************

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {   
            
            //ADD*******************************************  
            string[] m_strFileNames;
            string ListDir = "";
            Uri myUri = new Uri(RemoteHost);
            string host = myUri.Host;
            IPHostEntry hostInfo = Dns.GetHostEntry(host);
            ip = hostInfo.AddressList[0].ToString();
            try
            {
                m_strFileNames = Login();
                for (int i = 0; i <= m_strFileNames.Length - 1; i++)
                {
                    ListDir += m_strFileNames[i] + "\r\n";
                };
                textBox1.Text = ListDir;
                return;
            }
            catch (Exception ex)
            {
                textBox1.Text = ex.Message + "\r\n" + ex.StackTrace;
                return;
            }
            //ADD******************************************* 

        }
        //登録とファイル名取得
        public string[] Login()
        {
            socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), 21);
            // 接続
            try
            {
                socketControl.Connect(ep);
            }
            catch (Exception)
            {
                throw new IOException("Couldn't connect to remote server");
            }
            ReadReply();
            // 登録
            SendCommand("USER " + UserName);
            SendCommand("PASS " + Password);
            SendCommand("PASV");
            int index1 = strReply.IndexOf('(');
            int index2 = strReply.IndexOf(')');
            string ipData =
             strReply.Substring(index1 + 1, index2 - index1 - 1);
            string[] parts = ipData.Split(',');
            int len = ipData.Length;
            string ipAddress = parts[0] + "." + parts[1] + "." +
             parts[2] + "." + parts[3];
            int port = (Int32.Parse(parts[4]) << 8) + Int32.Parse(parts[5]);
            Socket s = new
             Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep2 = new
             IPEndPoint(IPAddress.Parse(ipAddress), port);
            try
            {
                s.Connect(ep2);
            }
            catch (Exception)
            {
                throw new IOException("Can't connect to remote server");
            }

            SendCommand("LIST " + RemotePath);
            //結果を取得
            strMsg = "";
            while (true)
            {
                    int iBytes = s.Receive(buffer, buffer.Length, 0);
                    strMsg += Encoding.GetEncoding(932).GetString(buffer, 0, iBytes);
                    if (iBytes <= 0)
                    {
                        break;
                    }               
            }
            char[] seperator = { '\n' };
            string[] strsFileList = strMsg.Split(seperator);
            List<string> directory = new List<string>();
            string[] temp = null;
            for (int i = 0; i < strsFileList.Length; i++)
            {
                if (strsFileList[i].Contains("<DIR>"))
                {
                    temp = strsFileList[i].Trim().Split(new string[] { "<DIR>" }, StringSplitOptions.None);
                    directory.Add(temp[1].Trim());
                    temp = null;
                }
            }
            s.Close();
            return directory.ToArray();

        }
        //サーバーから、strMsg取得
        private bool ReadReply()
        {
            strMsg = "";
            strReply = ReadLine();
            if (strReply == "Error")
            {
                return false;
            }
            return true;
        }
        //  Socket   からデータを受信して受信バッファーのリストに格納します。
        private string ReadLine()
        {
            while (true)
            {

                    int iBytes = socketControl.Receive(buffer, buffer.Length, 0);
                    strMsg += ASCII.GetString(buffer, 0, iBytes);
                    if (iBytes < buffer.Length)
                    {
                        break;
                    }
            }
            char[] seperator = { '\n' };
            string[] mess = strMsg.Split(seperator);
            if (strMsg.Length > 2)
            {
                strMsg = mess[mess.Length - 2];

            }
            else
            {
                strMsg = mess[0];
            }
            if (!strMsg.Substring(3, 1).Equals(" "))
            {
                return ReadLine();
            }
            return strMsg;
        }
        //送信する
        private bool SendCommand(string strCommand)
        {
            Byte[] cmdBytes = ASCII.GetBytes((strCommand + "\r\n").ToCharArray());
            socketControl.Send(cmdBytes, cmdBytes.Length, 0);
            return ReadReply();
        }
    }
}

#1


还是自己来吧!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FTPTest
{
    public partial class Form1 : Form
    {

        //ADD*******************************
        //変数の宣言
        public Socket socketControl;
        public int iReplyCode;
        public string strReply;
        string RemoteHost = @"ftp://xxxxxxx";
        string UserName = "xxxxxx"; 
        string Password = "xxxxxxx";    

        string RemotePath = "/";
        public string strMsg;
        Byte[] buffer = new Byte[5000];
        Encoding ASCII = Encoding.Default;
        public string ip;
        //ADD*******************************

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {   
            
            //ADD*******************************************  
            string[] m_strFileNames;
            string ListDir = "";
            Uri myUri = new Uri(RemoteHost);
            string host = myUri.Host;
            IPHostEntry hostInfo = Dns.GetHostEntry(host);
            ip = hostInfo.AddressList[0].ToString();
            try
            {
                m_strFileNames = Login();
                for (int i = 0; i <= m_strFileNames.Length - 1; i++)
                {
                    ListDir += m_strFileNames[i] + "\r\n";
                };
                textBox1.Text = ListDir;
                return;
            }
            catch (Exception ex)
            {
                textBox1.Text = ex.Message + "\r\n" + ex.StackTrace;
                return;
            }
            //ADD******************************************* 

        }
        //登録とファイル名取得
        public string[] Login()
        {
            socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), 21);
            // 接続
            try
            {
                socketControl.Connect(ep);
            }
            catch (Exception)
            {
                throw new IOException("Couldn't connect to remote server");
            }
            ReadReply();
            // 登録
            SendCommand("USER " + UserName);
            SendCommand("PASS " + Password);
            SendCommand("PASV");
            int index1 = strReply.IndexOf('(');
            int index2 = strReply.IndexOf(')');
            string ipData =
             strReply.Substring(index1 + 1, index2 - index1 - 1);
            string[] parts = ipData.Split(',');
            int len = ipData.Length;
            string ipAddress = parts[0] + "." + parts[1] + "." +
             parts[2] + "." + parts[3];
            int port = (Int32.Parse(parts[4]) << 8) + Int32.Parse(parts[5]);
            Socket s = new
             Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep2 = new
             IPEndPoint(IPAddress.Parse(ipAddress), port);
            try
            {
                s.Connect(ep2);
            }
            catch (Exception)
            {
                throw new IOException("Can't connect to remote server");
            }

            SendCommand("LIST " + RemotePath);
            //結果を取得
            strMsg = "";
            while (true)
            {
                    int iBytes = s.Receive(buffer, buffer.Length, 0);
                    strMsg += Encoding.GetEncoding(932).GetString(buffer, 0, iBytes);
                    if (iBytes <= 0)
                    {
                        break;
                    }               
            }
            char[] seperator = { '\n' };
            string[] strsFileList = strMsg.Split(seperator);
            List<string> directory = new List<string>();
            string[] temp = null;
            for (int i = 0; i < strsFileList.Length; i++)
            {
                if (strsFileList[i].Contains("<DIR>"))
                {
                    temp = strsFileList[i].Trim().Split(new string[] { "<DIR>" }, StringSplitOptions.None);
                    directory.Add(temp[1].Trim());
                    temp = null;
                }
            }
            s.Close();
            return directory.ToArray();

        }
        //サーバーから、strMsg取得
        private bool ReadReply()
        {
            strMsg = "";
            strReply = ReadLine();
            if (strReply == "Error")
            {
                return false;
            }
            return true;
        }
        //  Socket   からデータを受信して受信バッファーのリストに格納します。
        private string ReadLine()
        {
            while (true)
            {

                    int iBytes = socketControl.Receive(buffer, buffer.Length, 0);
                    strMsg += ASCII.GetString(buffer, 0, iBytes);
                    if (iBytes < buffer.Length)
                    {
                        break;
                    }
            }
            char[] seperator = { '\n' };
            string[] mess = strMsg.Split(seperator);
            if (strMsg.Length > 2)
            {
                strMsg = mess[mess.Length - 2];

            }
            else
            {
                strMsg = mess[0];
            }
            if (!strMsg.Substring(3, 1).Equals(" "))
            {
                return ReadLine();
            }
            return strMsg;
        }
        //送信する
        private bool SendCommand(string strCommand)
        {
            Byte[] cmdBytes = ASCII.GetBytes((strCommand + "\r\n").ToCharArray());
            socketControl.Send(cmdBytes, cmdBytes.Length, 0);
            return ReadReply();
        }
    }
}