我在C#工作,我有4个文件,如何一次上传所有文件? 我有这个,但这只适用于1档。
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("(secret)/keystock1.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("secret", "secret");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("keystock1.txt");
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("STOCK Upload File Complete, status {0}", response.StatusDescription);
response.Close();
答案 0 :(得分:0)
您可以使用Async
任务来实现此目的。像下面这样的类可以达到这个目的:
public class FileUploadsManager
{
//pass in the list of file paths which u want to upload.
public static async void UploadFilesAsync(string[] filePaths)
{
List<Task> fileUploadingTasks = new List<Task>();
foreach (var filePath in filePaths)
{
fileUploadingTasks.Add(UploadFileAsync(filePath));
}
await Task.WhenAll(fileUploadingTasks);
}
public static Task UploadFileAsync(string filePath)
{
return Task.Run(async () =>
{
//this is your code with a few changes
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(
string.Format("(secret)/{0}", Path.GetFileName(filePath))
);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("secret", "secret");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(filePath);
byte[] fileContents = Encoding.UTF8.GetBytes(await sourceStream.ReadToEndAsync());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = await request.GetRequestStreamAsync();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
Console.WriteLine("STOCK Upload File Complete, status {0}", response.StatusDescription);
response.Close();
});
}
}
您可以按如下方式调用:
string[] paths = new string[] { "C:\file1.txt", "C:\file2.txt", "C:\file2.txt" };
FileUploadsManager.UploadFilesAsync(paths);