【C#】ftp上傳文件的創(chuàng)建時(shí)間如何與本地文件創(chuàng)建時(shí)間保持一致
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
代碼如下: using System;
using System.IO;
using System.Net; class Program { static void Main(string[] args) { string localPath = "path_to_local_file"; // 本地文件路徑
FileInfo fileInfo = new FileInfo(localPath);
DateTime createTime = fileInfo.CreationTimeUtc; // 獲取本地文件的創(chuàng)建時(shí)間(UTC) using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential("ftp_username", "ftp_password"); // 設(shè)置FTP登錄信息
string remotePath = "/remote/directory/" + Path.GetFileName(localPath); // 指定要上傳到的遠(yuǎn)程目標(biāo)路徑及文件名 try { client.UploadFile(new Uri($"ftp://{client.BaseAddress}/{remotePath}"), localPath); // 上傳文件
// 修改上傳后的文件的創(chuàng)建時(shí)間為本地文件的創(chuàng)建時(shí)間
client.SetDateTimestamp(createTime);
Console.WriteLine("文件上傳成功!"); } catch (Exception ex) { Console.WriteLine("文件上傳失敗:" + ex.Message);
}
}
}
} 注意事項(xiàng): 需要引入命名空間 System.IO、System.Net; 將 "path_to_local_file" 替換為本地文件的完整路徑; 根據(jù)實(shí)際情況修改 FTP 服務(wù)器的主機(jī)名或 IP 地址、用戶名和密碼; 確保已經(jīng)添加了正確的網(wǎng)絡(luò)連接庫(kù)(比如 System.Net)。 該文章在 2024/1/26 23:08:09 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |