c#在ftping之前重命名文件

时间:2011-11-22 17:09:59

标签: c# ftp rename

如何将文件重命名为时间戳或随机唯一编号,然后再将其重命名为服务器?

示例:如果我选择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();

2 个答案:

答案 0 :(得分:4)

如果您只是希望文件上传使用其他名称而不在本地重命名,那么您是否只能更改

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

答案 1 :(得分:0)

使用FileInfo.MoveTo

toUpload.MoveTo(newName);