【问题标题】:FTP Async causes the file to be zero bytesFTP 异步导致文件为零字节
【发布时间】: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.UploadDataAsyncWebClient.UploadDataTaskAsync

标签: c# asynchronous async-await ftp


【解决方案1】:

导致问题的方法被同步调用

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多