我正在创建一个FTP客户端,允许我将文件上传到从组合框中选取的确定服务器。我的代码适用于单个文件,但尝试将其调整为多个文件一直是一项挑战。我已经阅读了有关异步上传的内容,但我无法通过我的头脑了解所以我们将非常感谢您的帮助。
private void upload(string filepath, string address, string username, string password)
{
//CONNECT
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address + "/" + Path.GetFileName(filepath));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
MessageBox.Show(response.WelcomeMessage + " to " + comboBox1.Text + " SERVER");
//PREPARE FILE
FileStream stream = File.OpenRead(filepath);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
//UPLOAD FILE
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
MessageBox.Show("Upload complete on " + comboBox1.Text + " SERVER " + response.StatusDescription);
}
我将要上传的文件放入ListBox,这是代码:
private void button2_Click(object sender, EventArgs e)
{
//THIS WAS FOR SINGLE FILE UPLOAD
//if (openFileDialog1.ShowDialog() == DialogResult.OK)
//textBox1.Text = openFileDialog1.FileName;
//MULTIPLE FILE UPLOAD
OpenFileDialog openFiles = new OpenFileDialog();
openFiles.Filter = "PDF, XML, TXT Files(*.pdf;*.xml;*.txt)|*.pdf;*.xml;*.txt|All Files(*.*)|*.*";
openFiles.Multiselect = true;
//openFiles.InitialDirectory = "C:\\";
//openFiles.RestoreDirectory = true;
openFiles.Title = "Select Files";
if (openFiles.ShowDialog() == DialogResult.OK)
{
foreach (string file in openFiles.FileNames)
{
listBox1.Items.Add(System.IO.Path.GetFileName(file));
}
}
}
现在,每当我点击"上传"我可以连接到服务器,但它不会传输文件错误是非常直接的:
无法找到文件' C:\ Users \ me \ documents \ visual studio 2010 \ Projects \ projectname \ project \ bin \ Debug \ openFileDialog1'。
但我无法完成这一部分。如何从ListBox引用我想要的文件路径? 这是我的" upload_click"代码,它只是我可以访问的3个服务器中的一个,但是一旦我得到第一个工作,其他的应该很容易。
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Text == "server" && listBox1.Items.Count > 0)
{
while (listBox1.Items.Count > 0)
{
upload(openFileDialog1.FileName, "ftp://000.000.0.000", "username", "password");
listBox1.Items.RemoveAt(0);
}
textBox1.Text = " ";
comboBox1.Text = "Select Server...";
pictureBox1.Image = null;
//listBox1.Items.Clear();
}
我觉得这只是一个简单的事情,但我无法看到它。
我做错了什么?
答案 0 :(得分:2)
填充列表框时,您将删除路径并仅包含文件名。
当您上传时,您只使用文件名并且路径丢失,因此程序会在默认目录中查找。
要验证,请在列表框中保留文件名的完整路径,看看它是否有效。
要修复,如果您不希望它们显示在列表框中,您必须将完整路径保存在某处。
答案 1 :(得分:0)
添加史蒂夫的回答:
我创建了一个列表List<string> fullFileName
来保存文件的完整路径。然后在打开OpenFileDialog
时,我用
fullFileName = new List<string>(openFiles.FileNames)
然后对于选中的每个文件,我在listBox
中添加了文件名,删除了listBox1.Items.Add(Path.GetFileNameWithoutExtension(file))
然后,对于upload
方法参数,我只使用了存储在列表中的路径
fullFileName[listBox1.SelectedIndex]
并将request.KeepAlive = false;
更改为request.KeepAlive = true;
因为我计划发送大量文件,如果我保持连接存活很长时间它会在一段时间后死亡,所以我想建议打开和关闭每个上传文件的请求。