如何通过FTP覆盖文件

use*_*720 1 c# ftp

我的程序生成txt文件,我将其上传到FTP。在文件名下,我有一个时间跨度(无秒)。

因此,当我在一分钟内两次生成文件时,我具有相同的文件名。并且,如果此类文件存在于ftp上,我将无法发送新文件,引发异常。

但是我只需要静默覆盖它即可。如何做到这一点?

目前我使用这样的功能

public bool FtpUploadFile(string filePath, FTPParameters ftpParams)
{
    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpParams.Server + "/" + ftpParams.Folder + "/" + filePath);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UsePassive = false;

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential(ftpParams.User, ftpParams.Password);

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(Path.Combine(Context.Current.SystemSettings.StorePath, filePath));
    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    sourceStream.Close();
    request.ContentLength = fileContents.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    return response.ExitMessage.Trim() == string.Empty;
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*mar 6

你不能。您必须先删除现有文件。我建议您重命名服务器上已经存在的文件,然后上传然后再上传新文件,只有成功后才删除旧文件,以确保还剩下一个文件。