我在ftp服务器上有一些zip文件,我想通过代码下载,但每次下载并尝试打开它们都会损坏。
FtpClient conn = new FtpClient();
conn.Host = ftpFtpServerAddress;
conn.Credentials = new NetworkCredential(ftpSrcUsername, ftpSrcPwd);
var files = conn.GetListing(ftpSrcFolder, FtpListOption.Modify | FtpListOption.Size);
foreach (var file in files)
{
conn.BeginOpenRead(file.FullName,
new AsyncCallback(BeginOpenReadCallback), new AsyncArguments()
{
Client = conn,
FileName = file.Name
});
}
private void BeginOpenReadCallback(IAsyncResult ar)
{
AsyncArguments args = (AsyncArguments)ar.AsyncState;
FtpClient conn = args.Client;
Stream istream = conn.EndOpenRead(ar);
using (System.IO.FileStream fs = System.IO.File.Create(@"C:\temp\" + args.FileName))
{
byte[] bytes = new byte[istream.Length + 10];
int numBytesToRead = (int)istream.Length;
fs.Write(bytes, 0, numBytesToRead);
}
}
答案 0 :(得分:0)
现在使用stream.Read。虽然这种方法对于小文件是可以的,但是你不应该将它用于非常大的文件,因为它会非常快地填满你的内存,并且大于2 gb的文件的字节大小不能存储为int32。
private void BeginOpenReadCallback(IAsyncResult ar)
{
AsyncObject args = (AsyncObject)ar.AsyncState;
FtpClient conn = args.conn;
Stream istream = conn.EndOpenRead(ar);
using (System.IO.FileStream fs = System.IO.File.Create(@"C:\temp\" + args.filename))
{
byte[] bytes = new byte[istream.Length];
int bytesread = istream.Read(bytes, 0, bytes.Length);
fs.Write(bytes, 0, bytesread);
}
}