简体   繁体   English

上传到 FTP,不使用匿名 C#

[英]Upload to FTP, not using anonymous C#

I used the following example code to upload to an FTP, it turns out that the server don't want to use anonymous connection, but I can't figure out how to change it to be able to upload with out breaking that rule.我使用以下示例代码上传到 FTP,结果发现服务器不想使用匿名连接,但我不知道如何更改它才能在不违反该规则的情况下上传。

// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/" + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;

// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("username", "password");

// Copy the contents of the file to the request stream.
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(file))
{
   fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}

request.ContentLength = fileContents.Length;

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(fileContents, 0, fileContents.Length);
}

using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
}

Anonymous credentials are still credentials.匿名凭据仍然是凭据。 You can get rid of them by removing the line您可以通过删除该行来摆脱它们

request.Credentials = new NetworkCredential("username", "password");

and you won't be sending any credentials to the server at all.并且您根本不会向服务器发送任何凭据。

Nevertheless, as mentioned in "Remarks" section of the MSDN docs , FtpWebRequest class is not recommended to be used for new development.尽管如此,如MSDN 文档的“备注”部分所述,不建议将 FtpWebRequest 类用于新开发。 Microsoft recommends to use one of third-party libraries listed here . Microsoft 建议使用此处列出的第三方库之一。

I also recommend choosing one of those, as they provide more robust way to communicate with FTP servers.我还建议选择其中之一,因为它们提供了更强大的与 FTP 服务器通信的方式。 You can enable logging and it will be easier for you to see why exactly your communication with the server is failing.您可以启用日志记录,这样您就可以更轻松地了解与服务器的通信失败的确切原因。 You will see all the commands your app is sending to the server and also all the responses from the server.您将看到您的应用程序发送到服务器的所有命令以及来自服务器的所有响应。 These libraries also implement all the basic operations like listing, downloading, uploading, permission setting, sync/async etc, so you don't have to write them yourself.这些库还实现了所有的基本操作,如列表、下载、上传、权限设置、同步/异步等,因此您不必自己编写它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM