【发布时间】:2020-01-31 10:34:10
【问题描述】:
我正在尝试使用异步等待来上传文件(文件作为字节数组传递)。我有一个运行正常的同步版本,但异步版本在 FTP 服务器上创建了一个文件,但字节为零。
同步版本
public virtual void UploadFile(IFile file)
{
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create("ftp://someFtpsite.com");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = Credentials;
request.ContentLength = file.FileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(file.FileContents, 0, file.FileContents.Length);
}
}
异步
public virtual async Task UploadFileAsync(IKCFile file)
{
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create("ftp://someFtpsite.com");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = Credentials;
request.ContentLength = file.FileContents.Length;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await requestStream.WriteAsync(file.FileContents, 0, file.FileContents.Length);
await requestStream.FlushAsync();
}
}
【问题讨论】:
-
在请求中添加以下内容:request.UseBinary = true;
-
@jdweng 这是默认值——即使不是,如果同步代码有效,为什么它会与异步代码有所不同?
-
@Rhodes73 我已经用
byte[]缓冲区而不是file.FileContents测试了你的代码,它对我来说可以正常工作=> 我们需要minimal reproducible example。 + 顺便说一句,你为什么不直接使用WebClient.UploadDataAsync或WebClient.UploadDataTaskAsync?
标签: c# asynchronous async-await ftp