2012年1月17日 星期二

[C#] How to Use FTP To Upload Files

localFile is the local file location. For example: C:\Windows\System32\notepad.exe
ftpUri is the remote FTP site. For example: ftp://localhost/home/
username and password are your FTP credentials.

To use FTP to upload files, we need to create a FtpWebRequest object:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetRemoteFileUri(localFile, ftpUri));
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
GetRemoteFileUri() method will combine localFile and ftpUri as your remote file uri. For example:
ftp://localhost/home/notepad.exe
It's very important. The rest is straightforward.
FileStream fileStream = File.OpenRead(localFile);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
fileStream.Close();

Stream ftpStream = request.GetRequestStream();
ftpStream.Write(buffer, 0, buffer.Length);
ftpStream.Close();

沒有留言:

張貼留言