.net 上载多个FTP文件
要求,每天晚上上传1500张jpg图片,下面的代码多次打开和关闭连接,我想知道是否有更好的方法 …这是一个代码片段,因此这里有其他地方定义的变量.net 上载多个FTP文件,.net,ftp,ftpwebrequest,.net,Ftp,Ftpwebrequest,要求,每天晚上上传1500张jpg图片,下面的代码多次打开和关闭连接,我想知道是否有更好的方法 …这是一个代码片段,因此这里有其他地方定义的变量 Dim picClsRequest = DirectCast(System.Net.WebRequest.Create(ftpImagePath), System.Net.FtpWebRequest) Dim picClsStream As System.IO.Stream Dim picCount As Integer = 0 For i = 1
Dim picClsRequest = DirectCast(System.Net.WebRequest.Create(ftpImagePath), System.Net.FtpWebRequest)
Dim picClsStream As System.IO.Stream
Dim picCount As Integer = 0
For i = 1 To picPath.Count - 1
picCount = picCount + 1
log("Sending picture (" & picCount & " of " & picPath.Count & "):" & picDir & "/" & picPath(i))
picClsRequest = DirectCast(System.Net.WebRequest.Create(ftpImagePath & "/" & picPath(i)), System.Net.FtpWebRequest)
picClsRequest.Credentials = New System.Net.NetworkCredential(ftpUsername, ftpPassword)
picClsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
picClsRequest.UseBinary = True
picClsStream = picClsRequest.GetRequestStream()
bFile = System.IO.File.ReadAllBytes(picDir & "/" & picPath(i))
picClsStream.Write(bFile, 0, bFile.Length)
picClsStream.Close()
Next
一些评论:
是的,我知道picCount是多余的…那是深夜
ftpImagePath、picDir、ftpUsername、ftpPassword都是变量
是的,这是未加密的
这段代码工作得很好,我正在寻找优化
相关问题:如果您希望一次发送多个文件(如果顺序不重要),可以考虑异步发送文件。看看各种Begin*和End*方法,例如and等 此外,您还可以查看该属性,该属性用于保持连接处于打开/缓存状态以供重用
嗯,您还可以尝试创建一个巨大的tar文件,并通过一个连接在一个流中发送单个文件;) 是否可以将文件压缩成不同的束,例如创建15个压缩文件,每个文件有100个图像,然后上载压缩文件,这样会更快、更高效
有免费的库可以动态创建zip(例如sharpZipLib)使用多线程-一次打开3-4个FTP连接并并行上载文件。使用一些第三方FTP客户端库怎么样?大多数协议并不试图隐藏FTP不是无状态协议(与FtpWebRequest不同) 下面的代码使用了我们的方法,但也有许多其他方法
// create client, connect and log in
Ftp client = new Ftp();
client.Connect("ftp.example.org");
client.Login("username", "password");
client.ChangeDirectory("/ftp/target/fir");
foreach (string localPath in picPath)
{
client.PutFile(localPath, Path.GetFileName(localPath));
}
client.Disconnect();
或者(如果所有源文件都在同一文件夹中):
注意:这段代码的问题是它一直在打开一个新的FTP连接。每次运行此应用程序时,它会打开和关闭1500次。
// create client, connect and log in
Ftp client = new Ftp();
client.Connect("ftp.example.org");
client.Login("username", "password");
client.PutFiles(
@"c:\localPath\*",
"/remote/path",
FtpBatchTransferOptions.Recursive,
FtpActionOnExistingFiles.OverwriteAll);
client.Disconnect();