FileStream.WriteAsync 问题

2019-01-02 21:14发布

先晒从ftp下载文件的代码

FileStream outputStream = new FileStream(@"C:\Users\LZQ\Desktop\ud33.unity3d", FileMode.Create);
FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri("ftp://192.168.1.100/U3D/Car.unity3d"));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("", "");
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponseAsync().Result;
Stream ftpStream = response.GetResponseStream();
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.ReadAsync(buffer, 0, bufferSize).Result;
while (readCount > 0)
{
outputStream.WriteAsync(buffer, 0, readCount);
readCount = ftpStream.ReadAsync(buffer, 0, bufferSize).Result;
}
ftpStream.Close();
outputStream.Close();
response.Close();

下载下来的unity3d文件打不开,
换成 outputStream.Write 方法后可以打开
有没有大神知道原因啊

2条回答
旧时光的记忆
2楼-- · 2019-01-02 21:25

需要在 outputStream.WriteAsync(buffer, 0, readCount); 之前加上 await

查看更多
步步皆殇っ
3楼-- · 2019-01-02 21:30
outputStream.WriteAsync(buffer, 0, readCount);
readCount = ftpStream.ReadAsync(buffer, 0, bufferSize).Result;   

这样的代码,执行起来的话实际效果是这样的
readCount = ftpStream.ReadAsync(buffer, 0, bufferSize).Result;
outputStream.WriteAsync(buffer, 0, readCount);

所以你得听楼上的人的话。

查看更多
登录 后发表回答