■■■

2016年4月5日火曜日

FTPサーバーからのダウンロードを途中から再開する方法

Visual C# 2008 逆引きクイックリファレンス Windows Vista/XP対応

FTPサーバーからのダウンロードを途中から再開する方法
VB.NET
Dim u As New Uri("ftp://localhost/test.txt")
Dim downFile As String = "C:\test.txt"

Dim ftpReq As System.Net.FtpWebRequest = _
    CType(System.Net.WebRequest.Create(u), System.Net.FtpWebRequest)
ftpReq.Credentials = New System.Net.NetworkCredential("username", "password")
ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
ftpReq.KeepAlive = False
ftpReq.UseBinary = False
ftpReq.UsePassive = False

Dim fs As System.IO.FileStream
If System.IO.File.Exists(downFile) Then
    '途中からのダウンロード
    ftpReq.ContentOffset = New System.IO.FileInfo(downFile).Length
    fs = New System.IO.FileStream( _
        downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write)
Else
    '通常ダウンロード
    fs = New System.IO.FileStream( _
        downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write)
End If

Dim ftpRes As System.Net.FtpWebResponse = _
    CType(ftpReq.GetResponse(), System.Net.FtpWebResponse)
Dim resStrm As System.IO.Stream = ftpRes.GetResponseStream()
Dim buffer(1024) As Byte
While True
    Dim readSize As Integer = resStrm.Read(buffer, 0, buffer.Length)
    If readSize = 0 Then
        Exit While
    End If
    fs.Write(buffer, 0, readSize)
End While
fs.Close()
resStrm.Close()

Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription)
ftpRes.Close()
Visual C# 2008 逆引きクイックリファレンス Windows Vista/XP対応

C#
Uri u = new Uri("ftp://localhost/test.txt");
string downFile = "C:\\test.txt";

System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
    System.Net.WebRequest.Create(u);
ftpReq.Credentials = new System.Net.NetworkCredential("username", "password");
ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftpReq.KeepAlive = false;
ftpReq.UseBinary = false;
ftpReq.UsePassive = false;

System.IO.FileStream fs;
if (System.IO.File.Exists(downFile))
{
    //途中からのダウンロード
    ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;
    fs = new System.IO.FileStream(
        downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);
}
else
{
    //通常ダウンロード
    fs = new System.IO.FileStream(
        downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
}

System.Net.FtpWebResponse ftpRes =
    (System.Net.FtpWebResponse)ftpReq.GetResponse();
System.IO.Stream resStrm = ftpRes.GetResponseStream();
byte[] buffer = new byte[1024];
while (true)
{
    int readSize = resStrm.Read(buffer, 0, buffer.Length);
    if (readSize == 0)
        break;
    fs.Write(buffer, 0, readSize);
}
fs.Close();
resStrm.Close();

Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
ftpRes.Close();
Visual C# 2008 逆引きクイックリファレンス Windows Vista/XP対応

■■■