English 中文(简体)
Retrieving a List of Files from an FTP server in C#
原标题:
  • 时间:2009-11-13 17:08:49
  •  标签:
  • c#
  • ftp

I m trying to retrieve a list of files from an FTP server, but I m getting some weird non-ASCII responses.

Here is the code that I am using:

 public string[] getFileList(string mask)
 {
   if(!logined)
   {
     login();
   }
   Socket cSocket = createDataSocket();
   this.getSslDataStream(cSocket);
   sendCommand("PASV");
   sendCommand("LIST " + "*"+mask);
   stream2.AuthenticateAsClient(remoteHost,
      null,
      System.Security.Authentication.SslProtocols.Ssl3 |
      System.Security.Authentication.SslProtocols.Tls,
      true);
   if(!(retValue == 150 || retValue == 125))
   {
     throw new IOException(reply.Substring(4));
   }
   StringBuilder mes = new StringBuilder();       
   while(true)
   {
     int bytes = cSocket.Receive(buffer, buffer.Length, 0);
     mes.Append(ASCII.GetString(buffer, 0, bytes));
     if(bytes < buffer.Length)
     {
       break;
     }
   }
   string[] seperator = {"
"};
   string[] mess = mes.ToString().Split(seperator, StringSplitOptions.RemoveEmptyEntries);
   cSocket.Close();
   readReply();
   if(retValue != 226)
   {
     throw new IOException(reply.Substring(4));
   }
   return mess;
 }

The response I get from the FTP server is this:

WRITE:PASV

READ:227 Entering Passive Mode (10,0,2,24,5,119)`

WRITE:LIST *.dat

READ:150 Opening ASCII mode data connection for /bin/ls.

READ:226 Transfer complete.

It stops there. The string array that it returns contains one index with some non-ascii characters. Looks like a bunch of garbage. Perhaps my ASCII.GetString part is wrong? I m not quite sure.

Thanks in advance.

问题回答

I wrote a pretty easy to use wrapper library for all the FtpWebRequest stuff. If you care to check it out, it s here https://gist.github.com/1242616

I use it in a lot of production environments and it hasn t failed me yet.

For what it s worth, the System.Net namespace has the FtpWebRequest and FtpWebResponse classes beginning in .Net 2.0.

Here s some code I ve used that writes the server s files to a local file:

...
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(address);
ftpRequest.Credentials = new NetworkCredential(username, password);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.KeepAlive = false;

FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

sr = new StreamReader(ftpResponse.GetResponseStream());
sw = new StreamWriter(new FileStream(fileName, FileMode.Create));

sw.WriteLine(sr.ReadToEnd());
sw.Close();

ftpResponse.Close();
sr.Close();
...
public Socket BuildDataConn(Socket FirstSocket)
{
    string ret = "";
    string RemoteIP = "";
    int RemotePort = 0;
    SendCommand("PASV");

    int id = 0;
    id = strMsg.LastIndexOf( ) );
    if (id != 0) 
    {
        string tmp = strMsg.Substring(strMsg.LastIndexOf( ( ) + 1, id - strMsg.LastIndexOf( ( ) - 1);
        string[] bByte = tmp.Split( , );
        RemotePort = int.Parse(bByte[4]) * 256 + Byte.Parse(bByte[5]);
        RemoteIP = bByte[0]+"." + bByte[1] + "." + bByte[2] + "." + bByte[3];
    }
    Socket NewConn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPEndPoint RemoteIPPort = new IPEndPoint(IPAddress.Parse(RemoteIP), RemotePort);
    try
    {
        NewConn.Connect(RemoteIPPort);
    }
    catch
    {
        throw new IOException("unable to Connect  !");
    }
    return NewConn;
}

Instead of using cSocket to receive response data,you need to get a second socket and then use the socket to receive response data. the second socket will response for sending back information. And make sure you had change your FTP working directory before you sendcommand LIST.

public List<string> GetFileNames()
{
    if (!bConnected)
    {
        Open();
    }
    List<string> retObj = new List<string>();
    Socket dataSock =  BuildDataConn(mySocket);

    SendCommand("NLST");
    string dataSockMsg = "";
    buffer = new byte[BLOCK_SIZE];

    while (true)
    {
        int iBytes = dataSock.Receive(buffer, buffer.Length, 0);
        dataSockMsg += System.Text.Encoding.ASCII.GetString(buffer, 0, iBytes);
        if (iBytes < buffer.Length)
        {
            break;
        }
    }

    string[] message = dataSockMsg.Split(new string[] { "
" }, StringSplitOptions.RemoveEmptyEntries);     

    dataSock.Close();

    foreach (string obj in message)
    {
        retObj.Add(obj);
    }

    return retObj;
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签