我和正在阅读此文件的其他所有人,如何将所有文件从联机目录列出到 ListView ?

这是要列出的本地目录的代码,我想知道是否有一种方法可以使它连接到FTP网站并列出文件?

FolderBrowserDialog folderPicker = new FolderBrowserDialog();
if (folderPicker.ShowDialog() == DialogResult.OK)
{

    ListView1.Items.Clear();

    string[] files = Directory.GetFiles(folderPicker.SelectedPath);
    foreach (string file in files)
    {

        string fileName = Path.GetFileNameWithoutExtension(file);
        ListViewItem item = new ListViewItem(fileName);
        item.Tag = file;

        ListView1.Items.Add(item);

    }

}

我已经使用了这段代码,但是我似乎无法使它正常工作,没有出现错误,但是也没有列出网络服务器上的文件?
private void ConnectBtn_Click(object sender, EventArgs e)
    {
        ListDirectory();
    }

    public string[] ListDirectory()
    {
        var list = new List<string>();

        var request = createRequest(TxtServer.Text, WebRequestMethods.Ftp.ListDirectory);

        using (var response = (FtpWebResponse)request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(stream, true))
                {
                    while (!reader.EndOfStream)
                    {
                        list.Add(reader.ReadLine());
                    }
                }
            }
        }

        return list.ToArray();
    }

    private FtpWebRequest createRequest(string uri, string method)
    {
        var r = (FtpWebRequest)WebRequest.Create(uri);

        r.Credentials = new NetworkCredential(TxtUsername.Text, TxtPassword.Text);
        r.Method = method;

        return r;
    }

最佳答案

您可以使用this wrapper library

相关代码为:

    public string[] ListDirectory() {
        var list = new List<string>();

        var request = createRequest(WebRequestMethods.Ftp.ListDirectory);

        using (var response = (FtpWebResponse)request.GetResponse()) {
            using (var stream = response.GetResponseStream()) {
                using (var reader = new StreamReader(stream, true)) {
                    while (!reader.EndOfStream) {
                        list.Add(reader.ReadLine());
                    }
                }
            }
        }

        return list.ToArray();
    }

关于c# - 将所有文件从在线FTP目录列出到 ListView C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13923193/

10-14 18:52