C# 异步下载问题
    public string IPAdress = "xx.xx.xx.xx";
public string ftpUser = "xxx";
public string ftpPassWord = "xxxxxxxx";
public string LocalAdress = "D://";
public string FileName = "xx.txt";

private void Upload()
{

    Uri uri = new Uri("ftp://" + IPAdress + "/" + FileName);     
    //定义FtpWebRequest,并设置相关属性
    FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);
    uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;

    uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);

    //开始以异步方式打开请求的内容流以便写入
    uploadRequest.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), uploadRequest);
}

private void EndGetStreamCallback(IAsyncResult ar)
{
    //用户定义对象,其中包含该操作的相关信息,在这里得到FtpWebRequest
    FtpWebRequest uploadRequest = (FtpWebRequest)ar.AsyncState;

    //结束由BeginGetRequestStream启动的挂起的异步操作
    //必须调用EndGetRequestStream方法来完成异步操作
    //通常EndGetRequestStream由callback所引用的方法调用
    Stream requestStream = uploadRequest.EndGetRequestStream(ar);

    FileStream fileStream = File.Open(@""+LocalAdress + FileName, FileMode.Open);

    byte[] buffer = new byte[2048];
    int bytesRead;

    float size;
    while (true)
    {         
        bytesRead = fileStream.Read(buffer, 0, buffer.Length);
        startbye += bytesRead;
        if (bytesRead == 0)
            break;
        Debug.Log(startbye);
        size = fileStream.Length;

        //本地的文件流数据写到请求流
        requestStream.Write(buffer, 0, bytesRead);
    }

    requestStream.Close();
    fileStream.Close();

    //开始以异步方式向FTP服务器发送请求并从FTP服务器接收响应
    uploadRequest.BeginGetResponse(new AsyncCallback(EndGetResponseCallback), uploadRequest);
}

private void EndGetResponseCallback(IAsyncResult ar)
{
    FtpWebRequest uploadRequest = (FtpWebRequest)ar.AsyncState;

    //结束由BeginGetResponse启动的挂起的异步操作
    FtpWebResponse uploadResponse = (FtpWebResponse)uploadRequest.EndGetResponse(ar);

    Debug.Log(uploadResponse.StatusDescription);
    Debug.Log("Upload complete");
}

    求教大神!!!!!如何把这段异步上传修改成异步下载!!!

1个回答

用不着改写这段代码,直接用 WebClient.DownloadFileAsync ,写一个回调委托函数,和你上面的做法类似
http://blog.csdn.net/youaregoo/article/details/8979149

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问