HOWTO · Csharp
C# で FTP にファイルをアップロードする
このガイドでは、C# でファイルを FTP にアップロードする方法を学習します。
このページの内容
このガイドでは、C# で FTP にファイルをアップロードする方法について説明します。 これは非常に簡単な手順です。
FTP の概念と基本をすでに理解していることを前提としています。 このガイドに飛び込みましょう。
C# で FTP にファイルをアップロードする
まず、ファイル パスを定義して文字列に格納し、その文字列を FileInfo に渡します。 2 番目のステップは、サーバー URL を定義することです。 ファイルをアップロードするフォルダに名前を付ける必要があります。
3 番目のステップは、これらのパスを 1つの URL に結合することです。
その後、ユーザー名とパスワードを入力し、先ほど作成した 1つの URL を FtpWebRequest に渡し、それを FtpWebRequest オブジェクト (この場合は req) 内に保存する必要があります。
アップロード の方法を選択する必要があります。 その後、資格情報を設定します。
最後のステップは、同じコンテンツを要求ストリームにコピーすることです。
// Path of file to be uploaded
string file_path = "Your File path ";
string PureFileName = new FileInfo(file_path).Name;
// Your Server url
string ftp_server_url = "Enter your server url";
// Name of folder in which you want to upload
// leave it empty if you want to upload to root directory/folder
string folder = "";
// combining the path
String uploadUrl = String.Format("{0}{1}/{2}", ftp_server_url, folder, PureFileName);
// username
string username = "Your Username";
// password
string password = "Your Password";
// creating ftp request
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(uploadUrl);
req.Proxy = null;
req.Method = WebRequestMethods.Ftp.UploadFile;
// setting ftp credentials
req.Credentials = new NetworkCredential(username, password);
req.UseBinary = true;
req.UsePassive = true;
// copy content to request stream
byte[] data = File.ReadAllBytes(file_path);
req.ContentLength = data.Length;
Stream stream = req.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
// status from ftp server
FtpWebResponse res = (FtpWebResponse)req.GetResponse();
return res.StatusDescription;