■■■

2016年4月4日月曜日

FTPServerにファイルをアップロードする方法

FTPServerにファイルをアップロードする方法
VB.NET
Dim upFile As String = "C:\test.txt"
Dim u As New Uri("ftp://localhost/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.UploadFile
ftpReq.KeepAlive = False
ftpReq.UseBinary = False
ftpReq.UsePassive = False

Dim reqStrm As System.IO.Stream = ftpReq.GetRequestStream()
Dim fs As New System.IO.FileStream( _
upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim buffer(1023) As Byte
While True
Dim
readSize As Integer = fs.Read(buffer, 0, buffer.Length)
If readSize = 0 Then
Exit While
End If

reqStrm.Write(buffer, 0, readSize)
End While
fs.Close()
reqStrm.Close()

Dim ftpRes As System.Net.FtpWebResponse = _
CType(ftpReq.GetResponse(), System.Net.FtpWebResponse)
Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription)
ftpRes.Close()
C#
string upFile = "C:\\test.txt";
Uri u = new Uri("ftp://localhost/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.UploadFile;
ftpReq.KeepAlive = false;
ftpReq.UseBinary = false;
ftpReq.UsePassive = false;

System.IO.Stream reqStrm = ftpReq.GetRequestStream();
System.IO.FileStream fs = new System.IO.FileStream(
upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] buffer = new byte[1024];
while (true)
{
int readSize = fs.Read(buffer, 0, buffer.Length);
if (readSize == 0)
break;
reqStrm.Write(buffer, 0, readSize);
}
fs.Close();
reqStrm.Close();

System.Net.FtpWebResponse ftpRes =
(System.Net.FtpWebResponse)ftpReq.GetResponse();
Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
ftpRes.Close();

■■■