我的FTP服务器上有一个文件夹,我想用该文件夹内的内容填充ComboBox
。我将如何去做?
string result = string.Empty;
//Request location and server name---------->
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://*******" +"/" + "Products" + "/");
//Lists directory
request.Method = WebRequestMethods.Ftp.ListDirectory;
// set credentials
request.Credentials = new NetworkCredential("user1","1234");
//initialize response
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//reader to read response
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
combobox1.Text = FTP_Server();
//data from file.
result = reader.ReadToEnd();
reader.Close();
response.Close();
谢谢!我什至不知道这是否有可能!
答案 0 :(得分:2)
按行阅读清单:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://example.com/remote/path/");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("username", "password");
comboBox1.BeginUpdate();
try
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
comboBox1.Items.Add(reader.ReadLine());
}
}
}
finally
{
comboBox1.EndUpdate();
}
如果有很多条目,将整个列表下载到一个字符串中,然后将其拆分(如另一个答案所建议的那样)可能会非常无效。
答案 1 :(得分:0)
在不知道您的响应字符串的确切格式的情况下,我的直觉是分割响应字符串:
string files[] = result.Split("\r\n");
然后遍历各个文件,将它们添加到combobox1的Items
:
// Depending on how many items you're adding, you may wish to prevent a repaint until the operation is finished
combobox1.BeginUpdate();
foreach(string file in files)
{
combobox1.Items.Add(file);
}
combobox1.EndUpdate();
那应该为您解决! MSDN上也有一些出色的(详尽的)文档,其中通常会包含一些用法示例以帮助您进一步了解:https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox(v=vs.110).aspx#Examples
请注意,如果最终想要显示来自其他FTP响应的信息,则必须像这样首先清除combobox1:combobox1.Items.Clear();