先晒从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 方法后可以打开
有没有大神知道原因啊
需要在 outputStream.WriteAsync(buffer, 0, readCount);
之前加上 await
不加 await 是不是写入的顺序会乱
outputStream.WriteAsync(buffer, 0, readCount);
readCount = ftpStream.ReadAsync(buffer, 0, bufferSize).Result;
这样的代码,执行起来的话实际效果是这样的
readCount = ftpStream.ReadAsync(buffer, 0, bufferSize).Result;
outputStream.WriteAsync(buffer, 0, readCount);
所以你得听楼上的人的话。
await outputStream.WriteAsync(buffer, 0, readCount);
readCount = ftpStream.ReadAsync(buffer, 0, bufferSize).Result;
这样的话感觉跟不用异步方法一样了
@左眼水星:
说句不是很好听的话,你明显不熟悉异步代码,最好能在写完这份代码,正常工作完成后,
好好多看看微软的异步代码教程,或者干脆别用异步代码。
异步代码需要程序员对异步有一定的理论理解能力。如果不能理解,多看别人怎么写得也行。