我正在使用以下代码来学习如何使用FTP加载文件。如何设置文件上传路径或文件夹?
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
该文件夹是您设置在创建网址的一部分request:"ftp://www.contoso.com/test.htm"。如果使用,"ftp://www.contoso.com/wibble/test.htm"则文件将被上传到名为的文件夹中wibble。
如果Method = WebRequestMethods.Ftp.MakeDirectory该wibble文件夹尚不存在,则可能需要先使用请求创建文件夹。