简体   繁体   中英

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.

// 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. Microsoft recommends to use one of third-party libraries listed here .

I also recommend choosing one of those, as they provide more robust way to communicate with FTP servers. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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