Jump to content


Photo

Ftp Client Desenvolvido Em Vb.net


  • Faça o login para participar
5 replies to this topic

#1 spynet

spynet

    Turista

  • Usuários
  • 25 posts
  • Sexo:Masculino

Posted 11/02/2008, 20:14

Olá pessoal, blz?
To precisando desenvolver um aplicativo de FTP Client que faça o seguinte:
Conecte no ftp do meu site que tah na locaweb e liste as fotos .JPG de um diretorio do server local e compare com as fotos .JPG que já tem no servidor da web e caso não tenha algum arquivo com o mesmo nome, ele faça upload automaticamente.

Tipo:

server local: server web:
001.jpg = 001.jpg
002.jpg = 002.jpg
003.jpg = não tem, faz upload
004.jpg = 004.jpg
005.jpg = não tem, faz uload

Já vasculhei a internet e não encontro nada que possa me dar um start no projeto.

Se alguém puder me dar um help, agradeceria.


[]s,
Adilson

#2 MACUL

MACUL

    Doutor

  • Usuários
  • 770 posts
  • Sexo:Masculino
  • Localidade:SP

Posted 13/02/2008, 15:42

http://www.example-c...bdotnet/ftp.asp

vb.net
Dim ftp As New Chilkat.Ftp2()

Dim success As Boolean

'  Any string unlocks the component for the 1st 30-days.
success = ftp.UnlockComponent("Anything for 30-day trial")
If (success <> true) Then
	MsgBox(ftp.LastErrorText)
	Exit Sub
End If


ftp.Hostname = "ftp.chilkatsoft.com"
ftp.Username = "****"
ftp.Password = "****"

'  The default data transfer mode is "Active" as opposed to "Passive".

'  Connect and login to the FTP server.
success = ftp.Connect()
If (success <> true) Then
	MsgBox(ftp.LastErrorText)
	Exit Sub
End If


'  Change to the remote directory where the file will be uploaded.
success = ftp.ChangeRemoteDir("junk")
If (success <> true) Then
	MsgBox(ftp.LastErrorText)
	Exit Sub
End If


'  Upload a file.
Dim localFilename As String
localFilename = "hamlet.xml"
Dim remoteFilename As String
remoteFilename = "hamlet.xml"

success = ftp.PutFile(localFilename,remoteFilename)
If (success <> true) Then
	MsgBox(ftp.LastErrorText)
	Exit Sub
End If


ftp.Disconnect()

MsgBox("File Uploaded!")

http://www.example-c.../csharp/ftp.asp

C#
Chilkat.Ftp2 ftp = new Chilkat.Ftp2();

bool success;

//  Any string unlocks the component for the 1st 30-days.
success = ftp.UnlockComponent("Anything for 30-day trial");
if (success != true) {
	MessageBox.Show(ftp.LastErrorText);
	return;
}

ftp.Hostname = "ftp.chilkatsoft.com";
ftp.Username = "****";
ftp.Password = "****";

//  The default data transfer mode is "Active" as opposed to "Passive".

//  Connect and login to the FTP server.
success = ftp.Connect();
if (success != true) {
	MessageBox.Show(ftp.LastErrorText);
	return;
}

//  Change to the remote directory where the file will be uploaded.
success = ftp.ChangeRemoteDir("junk");
if (success != true) {
	MessageBox.Show(ftp.LastErrorText);
	return;
}

//  Upload a file.
string localFilename;
localFilename = "hamlet.xml";
string remoteFilename;
remoteFilename = "hamlet.xml";

success = ftp.PutFile(localFilename,remoteFilename);
if (success != true) {
	MessageBox.Show(ftp.LastErrorText);
	return;
}

ftp.Disconnect();

MessageBox.Show("File Uploaded!");

*************** M ** A ** C ** U ** L ***************

*************************************************

#3 spynet

spynet

    Turista

  • Usuários
  • 25 posts
  • Sexo:Masculino

Posted 14/02/2008, 10:53

Tah dando o erro:
Type 'Chilkat.Ftp2' is not defined

É free o componente??? pois nao achei na toolbox do vs2005

[]s,
Adilson

#4 Nicholas Pufal

Nicholas Pufal

    Impossível: só existe até alguém duvidar e provar o contrário.

  • Usuários
  • 1655 posts
  • Sexo:Masculino
  • Localidade:Porto Alegre

Posted 15/02/2008, 17:32

Tah dando o erro:
Type 'Chilkat.Ftp2' is not defined

É free o componente??? pois nao achei na toolbox do vs2005

[]s,
Adilson


Hmm pelo que tá escrito no code é free por 30 dias, que é o período de trial.

Este é o site deles: http://www.chilkatsoft.com/
BLOG Touché Criação - Vamos trocar idéias? -> http://blog.touchecriacao.com.br/
// Links úteis: Busca || Regras
// Não respondo dúvidas via mensagem privada. Use o fórum para buscar ou perguntar.

#5 MACUL

MACUL

    Doutor

  • Usuários
  • 770 posts
  • Sexo:Masculino
  • Localidade:SP

Posted 16/02/2008, 14:21

http://msdn2.microso...hod(VS.80).aspx

C#
public static bool DeleteFileOnServer(Uri serverUri)
{
	// The serverUri parameter should use the ftp:// scheme.
	// It contains the name of the server file that is to be deleted.
	// Example: ftp://contoso.com/someFile.txt.
	// 
	
	if (serverUri.Scheme != Uri.UriSchemeFtp)
	{
		return false;
	}
	// Get the object used to communicate with the server.
	FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
	request.Method = WebRequestMethods.Ftp.DeleteFile;
 
	FtpWebResponse response = (FtpWebResponse) request.GetResponse();
	Console.WriteLine("Delete status: {0}",response.StatusDescription);  
	response.Close();
	return true;
}

Como o artigo não está disponíve vai aqui mesmo inteiro
(http://www.codeproje.../FtpClient.aspx)

Introduction
One annoying omission from the 1.x framework for .NET was support for FTP. This could be rectified by various libraries (some free, others commercial) that filled this gap. However, with Visual Studio 2005 and 2.0 of the .NET framework, FTP makes a welcome appearance.

As well as adding FTP, Microsoft has moved support for web, mail and FTP requests out of System.Web and into System.Net which is a more logical approach.

There is still a problem however: the FTP support isn't actually an FTP client, it's just support for the protocol in FtpWebRequest, in the same way as HttpWebRequest supports web requests. There is no "download a file" or "get a directory listing" function - you're still left to sort this out yourself.

This is where I hope my library FTPclient will come in useful. It's not a full-featured and comprehensive client but it provides all the most frequently used functions and can act as a base to add any missing ones if you need them.

Background
I assume here that you've got .NET 2.0 or one of the betas. This library was written on beta 2 of VS2005, so if you have a later version or the released version some changes may be required. I'll try to update the code if any framework changes break it.

I wrote this library to support my own application which needed to upload and download files to a supplier's FTP server: this runs on Linux, but I also tested it against the Microsoft FTP server that comes with NT and XP.

FTPClient Design
FTPclient is designed to operate in a stateless mode, in a similar way to how a web request would work. It does not hold open a connection but instead will connect, perform the requested action, and disconnect for each request.

This does mean it's very suitable for single-action operations but not ideal in performance terms if you want to hold open a connection while performing multiple requests. However the library could be adapted to operate in this way if someone is willing to take the time.

FtpWebRequest Basics
Making any type of FTP requests can be broken down into six steps:

Create a web request for a URL.
Set the login credentials (username, password).
Set the required options and the action to perform.
Upload data required (not used by some actions).
Download data or results (again, not used by some actions).
Close the request (and connection).
Although this might seem simple enough, there are several problems that can catch you out (they did for me!). One is that FtpWebRequest can support connections using the KeepAlive property, which is set to True by default. In my class it's turned off so that each connection is closed once the command completes.

An Example: Download a file
Here is an example of the steps in action, using FtpWebRequest to download a file:

Collapse'Values to use
Const localFile As String = "C:\myfile.bin"
Const remoteFile As String = "/pub/myftpfile.bin"
Const host As String = "ftp://ftp.myhost.com"
Const username As String = "myuserid"
Const password As String = "mypassword"

'1. Create a request: must be in ftp://hostname format,
' not just ftp.myhost.com
Dim URI As String = host & remoteFile
Dim ftp As System.Net.FtpWebRequest = _
CType(FtpWebRequest.Create(URI), FtpWebRequest)

'2. Set credentials
ftp.Credentials = New _
System.Net.NetworkCredential(username, password)

'3. Settings and action
ftp.KeepAlive = False
'we want a binary transfer, not textual data
ftp.UseBinary = True
'Define the action required (in this case, download a file)
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile

'4. If we were using a method that uploads data e.g. UploadFile
' we would open the ftp.GetRequestStream here an send the data

'5. Get the response to the Ftp request and the associated stream
Using response As System.Net.FtpWebResponse = _
CType(ftp.GetResponse, System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
'loop to read & write to file
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0 'see Note(1)
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using

'6. Done! the Close happens because ftp goes out of scope
' There is no .Close or .Dispose for FtpWebRequest

Note (1): I found that using Loop Until read < buffer.Size does not work because sometimes data less than the buffer size is returned by a remote server, and it was possible to have this condition true before the end of the stream is reached. I found that read = 0 seems to only occur once the stream is finished.

In this particular example, steps 1 and 2 would be repeated for any type of FTP operation in the same way, so I put them into a function that can be re-used. Step 3 is largely dependent on the operation you will perform, as is the type of upload or download, but I created a generic function GetResponseString that will read a textual response (e.g. a directory listing). This code also lacks any error handling.

Using FtpClient
To use FtpClient, create a new instance of the object, defining the host, username and password.

Dim myFtp As New FtpClient(hostname, username, password)

To get a directory listing of the FTP server's /pub directory:

Dim fullList As FtpDirectory = myFtp.GetDirectoryDetail("/pub/")

To determine which of these are files, use the GetFiles function:

Dim filesOnly As FtpDirectory = fullList.GetFiles()

To download or upload a file - a simple example:

myFtp.Download("/pub/myfile.bin", "C:\myfile.bin")
myFtp.Upload("C:\myfile.bin", "/pub/myfile.bin")

Or a more complex example, downloading all the files from a directory.

For Each file As FtpFileInfo In myFtp.GetDirectoryDetail("/pub/").GetFiles
myFtp.Download(file, "C:\" & file.Filename)
Next file

If a target file already exists for either uploads or downloads, the client will throw an exception by default to prevent unwanted overwrites. To turn off this behaviour, set the last, optional parameter PermitOverwrite to True.

Reading FTP Directories
Reading an FTP directory is simple enough: use either ListDirectory or ListDirectoryDetails request methods. ListDirectory is very simple - it returns a List(Of String) - but there is no distinction between a file or directory entry in the list so it may not be of use in most cases.

ListDirectoryDetails provides a lot more information about each file. It uses the detailed FTP listing which returns a collection of FtpFileInfo objects. An FtpFileInfo object contains the full path, name, date/time and file size of the entry as read from the detailed directory listing, in a similar way to FileInfo from System.IO.

Detailed FTP directory listings output varies according to the FTP server and the operating system it runs on. In particular, the NT/XP FTP server can be very different to UNIX and Linux results. The constructor for FtpFileInfo takes the text of the listing as a parameter and attempts to parse this with several regular expression patterns (held in _ParseFormats).

If you have errors with a particular FTP server reading detailed directories, you may need to add your own regular expressions to the _ParseFormats string array to get the library to work. I would expect the ones provided will work with most servers. Let me know if you find any new patterns that are needed.

Current Directory
I included the capability to store a current directory in the design in the same style as a standard FTP client application, although I've not used this myself. To set the directory, use FtpClient.CurrentDirectory = "/path". This comes into play if you don't specify a path for a remote file.

Dim myFtp As New FtpClient(hostname, username, password)
myFtp.CurrentDirectory = "/pub"
myFtp.Download("fileInPub.bin", "C:\test\fileInPub.bin")

myFtp.CurrentDirectory = "/pub/etc"
'will upload to file /pub/etc/MyFile.bin
myFtp.Upload("C:\MyFile.bin")

Possible Improvements
As mentioned already, this client does not support using an open connection, and has to log in for each request. In my application this wasn't a big issue, and I found the support for keeping the connection alive and performing multiple requests inadequately documented, so I decided to KISS (Keep It Simple).

Another improvement could be adding support for asynchronous operations which the FtpWebRequest object supports, but again KISS prevailed in my project.

Anyway, I hope you find this a useful little library that should do the basic operations you need for FTP.

License
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author
Howard Richards
*************** M ** A ** C ** U ** L ***************

*************************************************

#6 spynet

spynet

    Turista

  • Usuários
  • 25 posts
  • Sexo:Masculino

Posted 17/02/2008, 11:13

Que show....
Vou começar a desenvolver algo.....

[]s, e obrigado.

Adilson




1 user(s) are reading this topic

0 membro(s), 1 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq