■■■

2016年4月4日月曜日

FTPサーバーに接続する方法

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 ftpRes As System.Net.FtpWebResponse = _
CType(ftpReq.GetResponse(), System.Net.FtpWebResponse)
Dim resStrm As System.IO.Stream = ftpRes.GetResponseStream()
Dim fs As New System.IO.FileStream( _
downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim buffer(1023) 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()
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.Net.FtpWebResponse ftpRes =
(System.Net.FtpWebResponse)ftpReq.GetResponse();
System.IO.Stream resStrm = ftpRes.GetResponseStream();
System.IO.FileStream fs = new System.IO.FileStream(
downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
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();
■■■