在C#中创建一个任务来使用FTP上传文件的方法如下:
string ftpServer = "ftp://ftp.example.com";
string username = "username";
string password = "password";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer);
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.UploadFile;
string filePath = "path/to/file.txt";
byte[] fileContents = File.ReadAllBytes(filePath);
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
}
完整的代码示例:
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
string ftpServer = "ftp://ftp.example.com";
string username = "username";
string password = "password";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer);
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.UploadFile;
string filePath = "path/to/file.txt";
byte[] fileContents = File.ReadAllBytes(filePath);
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
}
}
}
这样就可以使用C#创建一个任务来使用FTP上传文件了。请注意,这只是一个简单的示例,实际应用中可能需要处理异常、添加错误处理等。另外,你还可以根据具体需求使用其他FTP相关的方法和属性,例如创建目录、删除文件等。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云