如何通过FTP覆盖文件 [英] How to overwrite file via FTP

查看:984
本文介绍了如何通过FTP覆盖文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My program generates txt file which i upload to FTP. In the name of the file i have an time span (without seconds).

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

So when i generate file twice in a minute i have same filename. And if such file exists on ftp, i cant send new one, exception raised.

但是我只需要默默地覆盖它.该怎么做?

But i just need to overwrite it silently. How this can be done?

目前我正在使用此类功能

Currently i use such func

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;
}

推荐答案

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

You can not. You have to delete the existing file first. I suggest you rename the file that already exists on the server, then upload then new file and only if that was successful you delete the old file to make sure you have at least one file left.

这篇关于如何通过FTP覆盖文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆