How to overwrite file via FTP

2019-07-27 09:52发布

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

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

标签: c# ftp
2条回答
何必那么认真
2楼-- · 2019-07-27 10:04

i tried it several times and it does overwrite the target here's my function

    public bool Upload(FileInfo fi, string targetFilename)
    {
        //copy the file specified to target file: target file can be full path or just filename (uses current dir)

        //1. check target
        string target;
        if (targetFilename.Trim() == "")
        {
            //Blank target: use source filename & current dir
            target = this.CurrentDirectory + fi.Name;
        }
        else if (targetFilename.Contains("/"))
        {
            //If contains / treat as a full path
            target = AdjustDir(targetFilename);
        }
        else
        {
            //otherwise treat as filename only, use current directory
            target = CurrentDirectory + targetFilename;
        }
          string URI = Hostname + target;

        //perform copy
        System.Net.FtpWebRequest ftp = GetRequest(URI);

        //Set request to upload a file in binary
        ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
        ftp.UseBinary = true;

        //Notify FTP of the expected size
        ftp.ContentLength = fi.Length;
    //    ftp.O

        //create byte array to store: ensure at least 1 byte!
        const int BufferSize = 2048;
        byte[] content = new byte[BufferSize - 1 + 1];
        int dataRead;

        //open file for reading
        using (FileStream fs = fi.OpenRead())
        {
            try
            {
                //open request to send
                using (Stream rs = ftp.GetRequestStream())
                {
                    do
                    {
                        dataRead = fs.Read(content, 0, BufferSize);
                        rs.Write(content, 0, dataRead);
                    } while (!(dataRead < BufferSize));
                    rs.Close();
                }

            }
            catch (Exception)
            {

            }
            finally
            {
                //ensure file closed
                fs.Close();
            }

        }


        ftp = null;
        return true;

    }
查看更多
我只想做你的唯一
3楼-- · 2019-07-27 10:22

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.

查看更多
登录 后发表回答