简体   繁体   中英

Renaming a File via FTP on C# program

Hi I'm having a problem on my C# program when I try to rename a file on a ftp site. It returns an error while performing the renaming process. But it can download the file that I try to rename as well as I can upload a file on the ftp server so I guess it's not about permission.

I also try to do it on command prompt using the same login that I used in my program and I didn't encounter any error. I successfully rename any file on it.

The error message is like this:

The remote server returned an error: (550) File unavailable (eg, file not found, no access).

Here is my code for renaming the file:

public void rename(string currentFileNameAndPath, string newFileName)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + currentFileNameAndPath);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = false;
        ftpRequest.KeepAlive = false;
        ftpRequest.Proxy = null;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.Rename;
        /* Rename the File */
        ftpRequest.RenameTo = newFileName;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Resource Cleanup */
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex) 
    { 
        MessageBox.Show(ex.ToString()); 
    }

    return;
}

好吧,我决定将文件移到新目录中而不是重命名,因为从一开始我的目标就是避免在上载新文件时覆盖原始文件。

I was getting an error trying to rename a file on an AS400 server: 'Syntax error in parameters or arguments'.

My problem was that I filled in the .RenameTo property with a full URI. Even shortening it to the folder path gave the same error. Since I did not want to move the file but just rename it, this worked for me:

string fileToMove = "ftp://127.0.0.1/Folder1/File.csv";
string renamedFile = "FileRenamed.old";

FtpWebRequest ftpRenameFile = (FtpWebRequest)WebRequest.Create(fileToMove);
ftpRenameFile.Credentials = new NetworkCredential(username, password);

ftpRenameFile.Method = WebRequestMethods.Ftp.Rename;
ftpRenameFile.RenameTo = renamedFile;   
ftpRenameFile.UseBinary = false;
ftpRenameFile.UsePassive = true; 

FtpWebResponse renameResponse = (FtpWebResponse)ftpRenameFile.GetResponse();

The renamed file stays in the same directory.

I've got the same error. I think your source file have got subfolders. These subfolders you have to remove in the target folder.

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