user3328720 user3328720 - 1 year ago 141
C# Question

How to overwrite file via FTP

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());
request.ContentLength = fileContents.Length;

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

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

return response.ExitMessage.Trim() == string.Empty;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download