gpt4 book ai didi

c# - 一次上传多个 Ftp 文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:09 25 4
gpt4 key购买 nike

我在 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();

最佳答案

您可以使用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);

关于c# - 一次上传多个 Ftp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27679283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com