Ir para o conteúdo
  • Revista PROGRAMAR: Já está disponível a edição #57 da revista programar. Faz já o download aqui!

jaferreira

upload vb para ftp

Mensagens Recomendadas

Asgorath    0
Asgorath
Option Explicit On
Option Strict On

Imports System.IO
Imports System.Net
Imports System.Text

Public Class SimpleFTPClient

    Public Function Download(ByVal destinationFile As String, ByVal downloadUri As Uri) As FtpStatusCode

        Try
            ' Check if the URI is and FTP site
            If Not (downloadUri.Scheme = Uri.UriSchemeFtp) Then
                Throw New ArgumentException("URI is not an FTp site")
            End If

            ' Set up the request
            Dim ftpRequest As FtpWebRequest = CType(WebRequest.Create(downloadUri), FtpWebRequest)

            ' use the provided credentials0
            If Me.m_isAnonymousUser = False Then
                ftpRequest.Credentials = New NetworkCredential(Me.m_userName, Me.m_password)
            End If

            ' Download a file. Look at the other methods to see all of the potential FTP features
            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile

            ' get the response object
            Dim ftpResponse As FtpWebResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
            Dim stream As Stream = Nothing
            Dim reader As StreamReader = Nothing
            Dim writer As StreamWriter = Nothing

            ' get the file as a stream from the response object and write it as 
            ' a file stream to the local PC
            Try
                stream = ftpResponse.GetResponseStream
                reader = New StreamReader(stream, Encoding.UTF8)
                writer = New StreamWriter(destinationFile, False)
                writer.Write(reader.ReadToEnd)
                Return ftpResponse.StatusCode
            Finally
                ' Allways close all streams
                stream.Close()
                reader.Close()
                writer.Close()
            End Try
        Catch ex As Exception
            Throw ex
        End Try

    End Function

    Public Property UserName() As String
        Get
            Return Me.m_userName
        End Get
        Set(ByVal value As String)
            Me.m_userName = value
        End Set
    End Property

    Public Property Password() As String
        Get
            Return Me.m_password
        End Get
        Set(ByVal value As String)
            Me.m_password = value
        End Set
    End Property

    Public Property IsAnonymousUser() As Boolean
        Get
            Return Me.m_isAnonymousUser
        End Get
        Set(ByVal value As Boolean)
            Me.m_isAnonymousUser = value
        End Set
    End Property

    Private m_userName As String
    Private m_password As String
    Private m_isAnonymousUser As Boolean

End Class

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites
Asgorath    0
Asgorath

para upload

using System;
using System.Net;
using System.Threading;

using System.IO;
namespace Examples.System.Net
{
    public class FtpState
    {
        private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;
        
        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }
        
        public ManualResetEvent OperationComplete
        {
            get {return wait;}
        }
        
        public FtpWebRequest Request
        {
            get {return request;}
            set {request = value;}
        }
        
        public string FileName
        {
            get {return fileName;}
            set {fileName = value;}
        }
        public Exception OperationException
        {
            get {return operationException;}
            set {operationException = value;}
        }
        public string StatusDescription
        {
            get {return status;}
            set {status = value;}
        }
    }
    public class AsynchronousFtpUpLoader
    {  
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;
            
            Uri target = new Uri (args[0]);
            string fileName = args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            
            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified. 
            // The example specifies the credential only to
            // control how actions are logged on the server.
            
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
            
            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;
            
            // Get the event to wait on.
            waitObject = state.OperationComplete;
            
            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback), 
                state
            );
            
            // Block the current thread until all operations are complete.
            waitObject.WaitOne();
            
            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            
            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                Console.WriteLine ("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback (EndGetResponseCallback), 
                    state
                );
            } 
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }
           
        }
        
        // The EndGetResponseCallback method  
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            FtpWebResponse response = null;
            try 
            {
                response = (FtpWebResponse) state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that 
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine ("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
    }
}

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites
Gooden    0
Gooden

que é esse codigo??? até me assustei meu deus o.0

Public Sub upload(ByVal adress As String, ByVal user As String, ByVal pass As String, ByVal file As String)
        Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(adress & file), System.Net.FtpWebRequest)
        With clsRequest
            .Credentials = New System.Net.NetworkCredential(user, pass)
            .Proxy = Nothing
            .Method = System.Net.WebRequestMethods.Ftp.UploadFile
        End With
        Dim bFile() As Byte = System.IO.File.ReadAllBytes( file)
        Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
        With clsStream
            .Write(bFile, 0, bFile.Length)
            .Close()
            .Dispose()
        End With
    End Sub

tao facil como isso .......

PS: Caraças la po geshi não sei fazer manualmente .-.-

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites
jaferreira    0
jaferreira

boas , ja consegui resolver , sera que tens ai para listar ficheiros e pastas de um ftp e para fazer o download tb ... ? agradecia abraço

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Crie uma conta ou ligue-se para comentar

Só membros podem comentar

Criar nova conta

Registe para ter uma conta na nossa comunidade. É fácil!

Registar nova conta

Entra

Já tem conta? Inicie sessão aqui.

Entrar Agora


×

Aviso Sobre Cookies

Ao usar este site você aceita a nossa Política de Privacidade