C# 当上传结束时查找
我有几个文件夹中的文件,我想上传到我的服务器。所有文件都在同一时间上载。我想找到的是最后一个文件何时上载到我的服务器。我的代码如下:C# 当上传结束时查找,c#,C#,我有几个文件夹中的文件,我想上传到我的服务器。所有文件都在同一时间上载。我想找到的是最后一个文件何时上载到我的服务器。我的代码如下: public void UploadFile() { // Only get subdirectories that begin with the letter "p." string[] dirs = Directory.GetFiles(path+ dataDir); int counter = 1; foreach (
public void UploadFile()
{
// Only get subdirectories that begin with the letter "p."
string[] dirs = Directory.GetFiles(path+ dataDir);
int counter = 1;
foreach (string dir in dirs) {
try{
// Get an instance of WebClient
WebClient client = new System.Net.WebClient();
//client.UploadProgressChanged += WebClientUploadProgressChanged;
client.UploadFileCompleted += WebClientUploadCompleted;
// parse the ftp host and file into a uri path for the upload
Uri uri = new Uri(m_FtpHost + new FileInfo(dir).Name);
// set the username and password for the FTP server
client.Credentials = new System.Net.NetworkCredential(m_FtpUsername, m_FtpPassword);
// upload the file asynchronously, non-blocking.
client.UploadFileAsync(uri, "STOR",dir);
}
catch(Exception e){
print(e.Message);
}
}
}
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
print( "Upload is finished. ");
}
正如现在一样,UploadFileCompleted是为每个文件分别调用的,但是我希望在上传所有文件时都有一个标志。如何执行此操作?您只需使用专用的“totalUploadCounter”变量检查所有上载何时完成:
private int totalUploadCounter = 0;
private int counter = 0;
public void UploadFile()
{
string[] dirs = Directory.GetFiles(path + dataDir);
totalUploadCounter = 0;
counter = 0;
foreach (var dir in dirs) {
totalUploadCounter += Directory.GetFiles(dir).Length;
}
// your upload code here
}
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
counter++;
if (counter == totalUploadCounter) {
// ALL UPLOADS FINISHED!!!
}
}
您可以改为使用UploadFileTaskAsync,然后等待所有返回的任务完成。在发送所有文件时调用UploadFile的方法中使用backgroundworker,如前所述。上传完成后为什么需要异步事件?我想知道这个解决方案是否存在“数据竞争”问题。请看这里: