不久前,我问了一个关于如何将文件从一个位置分块复制到另一个位置的问题:CopyFileEx“参数无效”错误
我收到了以下非常有帮助的代码。
static void chunkCopyFile(string source, string destination, int bytesPerChunk)
{
uint bytesRead = 0;
using (FileStream fs = new FileStream(source, FileMode.Open, FileAccess.Read)) {
using (BinaryReader br = new BinaryReader(fs)) {
using (FileStream fsDest = new FileStream(destination, FileMode.Create)) {
BinaryWriter bw = new BinaryWriter(fsDest);
byte[] buffer;
for (int i = 0; i < fs.Length; i += bytesPerChunk) {
buffer = br.ReadBytes(bytesPerChunk);
bw.Write(buffer);
bytesRead += Convert.ToUInt32(bytesPerChunk);
updateProgress(bytesRead);
}
}
}
}
}
但是,我现在需要将此代码转换为使用 FTP。我尝试了将FTP路径传递给文件流的明显方法,但它给了我一个错误,说“不支持”。
我已经设法获得文件长度,我只是不确定如何将下载分成块。一如既往地感谢任何帮助!
到目前为止的代码(不多)
static void chunkCopyFTPFile(string destination, int bytesPerChunk)
{
uint bytesRead = 0;
fWR = (FtpWebRequest)WebRequest.Create("ftp://" + FTP_SERVER_NAME + "/test.txt");
fWR.Method = WebRequestMethods.Ftp.DownloadFile;
fWR.UseBinary = true;
fWR.Credentials = new NetworkCredential(FTP_SERVER_USERNAME, FTP_SERVER_PASSWORD);
FtpWebResponse response = (FtpWebResponse)fWR.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sR = new StreamReader(responseStream);
sR.ReadToEnd();
sR.Close();
response.Close();
}
最终代码(工作):
using (Stream responseStream = response.GetResponseStream()) {
using (BinaryReader bR = new BinaryReader(responseStream)) {
using (FileStream fsDest = new FileStream(destination, FileMode.Create)) {
BinaryWriter bw = new BinaryWriter(fsDest);
int readCount;
byte[] buffer = new byte[bytesPerChunk];
readCount = responseStream.Read(buffer, 0, bytesPerChunk);
bytesRead += Convert.ToUInt32(readCount);
updateProgress(bytesRead);
while (readCount > 0) {
bw.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bytesPerChunk);
bytesRead += Convert.ToUInt32(readCount);
updateProgress(bytesRead);
}
}
}
}