How to rename a file after upload

14,796

RenameTo is a property, not a method. Your code should read:

// requestFTP has been set to null in the previous line
requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName));
requestFTP.Proxy = null;
requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);

string newFilename = fileName.Replace(".ftp", "");
requestFTP.Method = WebRequestMethods.Ftp.Rename;
requestFTP.RenameTo = newFilename;
requestFTP.GetResponse();
Share:
14,796
user198003
Author by

user198003

Updated on June 14, 2022

Comments

  • user198003
    user198003 almost 2 years

    I have to upload file using Ftp protocol on server, and rename uploaded file after uploading.

    I can upload it, but don't know how to rename it.

    Code looks like this:

    FtpWebRequest requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName));
    requestFTP.Proxy = null;
    
    requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
    requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
    FileStream fStream = fileInfo.OpenRead();
    int bufferLength = 2048;
    byte[] buffer = new byte[bufferLength];
    Stream uploadStream = requestFTP.GetRequestStream();
    int contentLength = fStream.Read(buffer, 0, bufferLength);
    while (contentLength != 0)
    {
      uploadStream.Write(buffer, 0, contentLength);
      contentLength = fStream.Read(buffer, 0, bufferLength);
    }
    uploadStream.Close();
    fStream.Close();
    
    requestFTP = null;
    
    string newFilename = fileName.Replace(".ftp", "");
    requestFTP.Method = WebRequestMethods.Ftp.Rename; // this like makes a problem
    requestFTP.RenameTo(newFilename);
    

    Error I'm getting is

    Error 2 Non-invocable member 'System.Net.FtpWebRequest.RenameTo' cannot be used like a method.

    • default
      default over 11 years
      both Method and Rename are strings. They are not functions.
    • Admin
      Admin over 11 years
      C# doesn't provide a direct rename method. You should copy the file with a new name in the server and delete the old file.
  • Sam
    Sam over 11 years
    Typically this approach is used to signify to polling applications that the file has finished uploading. The joys of FTP.
  • user198003
    user198003 over 11 years
    Tnx, but I really need to copy file with some tmp name, and after that to rename it to it's native name.
  • Christian
    Christian about 9 years
    Why not just answer the OP instead?