I have a question about Uploading to a FTP with C#.
What I want to do is if the file exists then I want to add like Copy or a 1 after the filename so it doesn't replace the file. Any Ideas?
var request = (FtpWebRequest)WebRequest.Create(""+destination+file);
request.Credentials = new NetworkCredential("", "");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
}
}
I am working on something similar. My problem was that:
was not really working. Sometimes it gave exception sometimes it didn't. And for the same file! Have no idea why.
I change it as Tedd said (thank you, btw) to
and it seems to work now.
There is no shortcut. You need to
dir
the target directory then use#
to determine which name you want to use.Since FTP control protocol is slow in nature (send-receive) I suggest first pulling directory content and checking against it before uploading the file. Note that dir can return two different standards: dos and unix
Alternatively you can use the
MDTM file
command to check if file already exist (used to retrieve timestamp of a file).It's not particularly elegant as I just threw it together, but I guess this is pretty much what you need?
You just want to keep trying your requests until you get a "ActionNotTakenFileUnavailable", so you know your filename is good, then just upload it.
Edit: Updated so this will work for any type of web request and is a little slimmer.