How to FTP a File to a Remote Server and Change Permissions

How to FTP a File to a Remote Server and Change Permissions

Are you trying to FTP a file but require a bit more functionality than the standard method offers? Having an especially difficult time finding that solution in the .NET 2.0 framework?

Recently, we worked with a client who needed to FTP files and then change permissions on the file. However, they were using .NET framework 2.0. The usual way to do this would be to use FTPWebRequest, but it doesn’t support the CHMOD command, so we had to find another way.

FTP Client Library

We found an open source library called FTPClient that quickly and easily solved the problem. This library supports both .NET 2.0 and .NET 4.0, has an easy to use interface and has many examples on its online resource page.

Visit to download.

This code snippet will write a local file to a remote FTP server, then change the permission on the file.

@ ignores all the escape characters
const string fileToBeRead = @"C:testmytest.txt";
const string remoteFile = @"C:FTPfolderremoteFile.txt";
//FTPClient can be downloaded at:
//https://netftp.codeplex.com/FtpClient ftpClient = new FtpClient
     {
          Host = "www.example.com",
          Credentials = new NetworkCredential("myUserName", "myPassword")
     };
ftpClient.Connect();//the reading and writing
using (var fileStream = File.OpenRead(fileToBeRead))
using (var outStream = ftpClient.OpenWrite(remoteFile))
     {
          var buffer = new byte[8 * 1024];
          int count;
          while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
          {
               outStream.Write(buffer, 0, count);
          }
     }
//let's change the folder and change a file's permission.
//Note that you have to be in the file's folder to change the permission
//Ie, you can't change it from a different level in the folder structure.
string cwd = ftpClient.GetWorkingDirectory();
cwd += "/" + "FTPFolder";
ftpClient.SetWorkingDirectory(cwd);
FtpReply reply;//change permission
if (!(reply = ftpClient.Execute("SITE chmod 775 " + "remoteFile.txt")).Success)
     {
          throw new FtpCommandException(reply);
     }

Suggested

Subscribe For More Content