c#重命名文件前ftp

本文关键字:ftp 文件 重命名 | 更新日期: 2023-09-27 18:15:21

如何在文件实际传输到服务器之前将其重命名为时间戳或随机唯一数字?

示例:如果我选择C:'taco.pdf .....1321981871.pdf实际上是要ftp到服务器的内容。

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();

c#重命名文件前ftp

如果您只是想以不同的名称上传文件而不需要在本地重命名,那么您不能直接更改

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

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

?

使用FileInfo.MoveTo:

toUpload.MoveTo(newName);