Jake H. Jake H. - 27 days ago 24
C# Question

c# rename file before ftping

How can I rename the file to a timestamp or random unique number before it is actually ftped to the server?

example: if i select C:\taco.pdf ..... 1321981871.pdf is actually what would be ftp'd to the server.

FileInfo toUpload = new FileInfo(this.txtFile.Text);

FtpWebRequest request =
(FtpWebRequest)WebRequest.Create(
"ftp://192.168.0.186" + "/" + toUpload.Name
);

request.Method = WebRequestMethods.Ftp.UploadFile;

request.Credentials =
new NetworkCredential("myuser","mypassword");

Stream ftpStream = request.GetRequestStream();
FileStream file = File.OpenRead(this.txtFile.Text);

int length = 1024;
byte[] buffer = new byte[length];
int bytesRead = 0;


do
{
bytesRead = file.Read(buffer, 0, length);
ftpStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);

file.Close();
ftpStream.Close();

Answer

If you just want the file uploaded with a different name without renaming it locally, couldn't you just change

 FtpWebRequest request = 
            (FtpWebRequest)WebRequest.Create( 
            "ftp://192.168.0.186" + "/" + toUpload.Name 
            ); 

to

 FtpWebRequest request = 
            (FtpWebRequest)WebRequest.Create( 
            "ftp://192.168.0.186/whatever file name you want"); 

?