2010-03-05 210 views
6

要求,每晚上传1500 jpg图片,下面的代码打开和关闭多次连接,我想知道是否有更好的方法。上传多个FTP文件

...这是一个代码片段,所以这里在别处

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都是变量

是的,这是不加密的

此代码工作正常,我在寻找优化

相关问题:FTP Upload multiple files without disconnect using .NET

+0

注:我有这个代码的问题是,它保持打开一个新的FTP连接。每次运行此应用时,它都会打开并关闭1500次。 – Markus 2010-03-15 18:33:17

回答

5

如果您想一次发送多个文件(如果顺序不重要),则可以异步发送文件。查看各种Begin *和End *方法,如FtpWebRequest.BeginGetResponseFtpWebRequest.EndGetResponse等。

此外,您可以查看FtpWebRequest.KeepAlive属性,该属性用于保持连接打开/缓存以供重用。

嗯,你也可以尝试创建一个巨大的tar文件,并与一个连接发送的单个文件在一个流;)

0

是否可以压缩文件在不同的束,例如创建15个zip文件,每个有100个图像,然后上传压缩文件,这样会更快,更高效。

有免费的图书馆动态创建ZIP(例如sharpZipLib)

0

使用多线程 - 在同一时间打开3-4 FTP连接和上传文件并行。

0

如何使用某个第三方FTP客户端库?他们中的大多数并不试图隐藏FTP不是一个无状态的协议(不像FtpWebRequest)。

以下代码使用我们的Rebex FTP/SSL,但其他许多人也是如此。

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

或者(如果您所有的源文件相同的文件夹):

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