上傳檔案
伺服器,您可以使用WebClient.UploadFile 或FtpWebRequest。要使用WebClient,只需提供FTP URL 和本機檔案路徑:
WebClient client = new WebClient(); client.Credentials = new NetworkCredential("username", "password"); client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
要進行更多控制,請使用FtpWebRequest:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.UploadFile; using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip")) using (Stream ftpStream = request.GetRequestStream()) { fileStream.CopyTo(ftpStream); }
下載檔案
要從FTP 伺服器下載文件,請使用WebClient.DownloadFile或FtpWebRequest。若要使用 WebClient,請提供 FTP URL 和本機檔案路徑:
WebClient client = new WebClient(); client.Credentials = new NetworkCredential("username", "password"); client.DownloadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
要進行更多控制,請使用 FtpWebRequest:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.DownloadFile; using (Stream ftpStream = request.GetResponse().GetResponseStream()) using (Stream fileStream = File.Create(@"C:\local\path\file.zip")) { ftpStream.CopyTo(fileStream); }
以上是如何使用 C#/.NET 向 FTP 伺服器上傳和下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!