上传文件
上传文件对于 FTP 服务器,您可以使用 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中文网其他相关文章!