【发布时间】:2014-04-07 07:42:02
【问题描述】:
我的程序生成我上传到 FTP 的 txt 文件。在文件名中,我有一个时间跨度(没有秒数)。
所以当我在一分钟内生成两次文件时,我的文件名相同。如果 ftp 上存在此类文件,我无法发送新文件,引发异常。
但我只需要默默地覆盖它。如何做到这一点?
目前我使用这样的功能
public bool FtpUploadFile(string filePath, FTPParameters ftpParams)
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpParams.Server + "/" + ftpParams.Folder + "/" + filePath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(ftpParams.User, ftpParams.Password);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(Path.Combine(Context.Current.SystemSettings.StorePath, filePath));
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return response.ExitMessage.Trim() == string.Empty;
}
【问题讨论】:
-
基于STORE (STOR) 和WebRequestMethods.Ftp.UploadFile 它应该创建或覆盖文件。