我是c#的新手并且正在使用此代码将单个文本文件(csv文件)上传到13个(摄像头)ftp位置。我不知道如何通过一键式点击事件来完成此操作。 我正在研究这个代码它适用于一个站点,但我怎么能为12个其他(摄像头)ftp位置做这个。如何在一个数组中传递mutliple ftp adddress
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");
}
}
}
答案 0 :(得分:0)
你有什么尝试?将代码放在接受FTP URL的方法中:
public void UploadBlacklistFile(string ftpServerUrl) { ... }
在循环遍历所有服务器名称的循环中调用该方法:
foreach (string serverUrl in serverUrls)
{
UploadBlacklistFile(serverUrl);
}
答案 1 :(得分:0)
这个问题有多种解决方案。一个显而易见的方法就是复制并粘贴你的代码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
}