我正在尝试了解FtpWebRequest的MSDN文档,更具体地说,how to upload using FTP and C#
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();
}
}
}
}
在上面的代码中,它们引用了2种文件类型。我是否正确地假设testfile.txt是'源'文件(在本地计算机上)并且test.htm也将重命名testfile.txt?
答案 0 :(得分:4)
是的 - 您正在将上传到 test.htm
,从 testfile.txt
加载数据。你可以告诉我,因为test.htm
是URL的一部分(因此是远程的),而testfile.txt
只是通过在文件上创建StreamReader
来加载。
(值得注意的是,顺便提一下,这个代码在各方面都非常糟糕 - 特别是在资源处置方面。不要将其视为体现最佳实践......)