上传文本文件到多个FTP服务器
本文关键字:FTP 服务器 文本 文件 | 更新日期: 2023-09-27 18:14:29
我是c#的新手,正在编写这段代码,将单个文本文件(csv文件)上载到13个(相机)ftp位置。我不知道如何做到这一点与一个按钮点击事件。我正在研究这段代码,它可以很好地用于一个网站,但我如何才能为其他12(相机)ftp位置做到这一点。如何在数组中传递多个FTP地址
private void button1_Click(object sender, EventArgs e)
{
UploadBlacklistFile(string ftpServerUrl,string filename);
}
void UploadBlacklistFile(string ftpServerUrl,string filename)
{
Boolean ftpMode = true;
//// Get the object used to communicate with the server.
//FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://158.125.161.83");
//request.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;
//// This example assumes the FTP site uses anonymous logon.
//request.Credentials = new NetworkCredential("superuser", "superuser");
if (ftpMode == true)
{
request.KeepAlive = false;
}
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("C://blacklist/ticketsblacklist.csv");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
string [] ftpaddress = ({"100.100.100.85","parm","parm"};{"101.101.101.85","parm1","parm1"})
foreach(string addr in ftpaddress)
{
uploadFile(addr, @"C:/blacklist/ticketsblacklist.csv");
}
}
}
你试过了吗?将代码放入一个接受FTP url的方法中:
public void UploadBlacklistFile(string ftpServerUrl) { ... }
并在循环中调用该方法其中循环遍历所有服务器名称:
foreach (string serverUrl in serverUrls)
{
UploadBlacklistFile(serverUrl);
}
这个问题有多种解决方案。一个明显的方法是复制粘贴你的代码12次(尽管这不是很干净,如果你这么做,codereview上的人可能会揍你一顿)。
我是这样做的:
-
创建一个方法(比如
UploadFile(string url, string filename)
)并复制所有的代码来完成文件上传。 -
创建一个字符串数组,存储所有FTP地址(例如
string[] addresses={"1.2.3.4","4.3.2.1",...};
) -
使用
foreach
循环遍历数组并调用函数foreach(string addr in addresses) { UploadFile(addr, @"C:'yourfile.txt"); }
应该可以。
更新关于用户名和密码的情况:
你最好这样写:
string[,] addresses =
{
{"100.100.100.85","username","password"},
{"100.100.100.86","username2","password2"},
// ...
};
foreach(string[] addr in addresses)
{
UploadFile(addr[0], addr[1], addr[2], @"C:'yourfile.txt");
}
void UploadFile(string address, string user, string password, string filename)
{
// upload
}