Application to download all files from a remote FTP directory

Asked

Viewed 231 times

0

I’m trying to make an installer-like application for a proprietary system.

The process it does is: creates a directory and two subdirectories on a PC that will use the system.

After creating the directory and the Ubdirectories, the application accesses ftp and downloads the executables that are in ftp for the Ubdirectories that are on the machine.

The code I’m using is as follows::

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace App_Install_Golden_Premium
{
    public partial class frmInstala : Form
    {
        public frmInstala()
        {
            InitializeComponent();
        }

        private void btInstalar_Click(object sender, EventArgs e)
        {
            string diretorio = @"C:\Program Files\Teste\";
            string subdiretorio;
            string diretorioFTP = string.Empty;
            string usuario;
            string senha;
            string arquivo = string.Empty;
            var pathWithEnv = @"%USERPROFILE%\Área de Trabalho";
            var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
            string dirDesktop = filePath;
            progressBar1.Value = 0;


            // Pega dominio/usuario logado atual
            string informacao = System.Security.Principal.WindowsIdentity.GetCurrent().Name; ;

            if (rbGolden.Checked)
            {
                subdiretorio = "Golden";
                diretorioFTP = "ftp://ftp.ftp remoto";
                usuario = "usuario";
                senha = "senha";
            }
            else
            {
                subdiretorio = "Premium";
                diretorioFTP = "ftp://ftp.ftp remoto";
                usuario = "usuario";
                senha = "senha";
            }

            diretorio += subdiretorio;

            if (Directory.Exists(diretorio))
            {
                if (MessageBox.Show("O Diretório já existe!\n- Se deseja SAIR, Clique em [CANCELAR]\n- Se deseja CONTINUAR, Clique em [REPETIR] ", "Criação de Diretorio", MessageBoxButtons.RetryCancel, MessageBoxIcon.Hand) == DialogResult.Cancel)
                {
                    Application.Exit();
                }
            }
            else
            {
                Directory.CreateDirectory(diretorio);

                DirectorySecurity regras = new DirectorySecurity();
                regras.AddAccessRule(new FileSystemAccessRule(informacao, FileSystemRights.FullControl, AccessControlType.Allow));

                MessageBox.Show("Diretório Criado com Sucesso!", "Criação de Diretório", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(diretorioFTP);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(usuario, senha);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            DirectoryInfo di = new DirectoryInfo(diretorioFTP);

            progressBar1.Maximum = di.GetFiles().Length;

            foreach( var item in di.GetFiles())
            {
                arquivo = Path.Combine(diretorio, item.Name);
                File.Copy(item.FullName, arquivo);
                lblStatus.Refresh();
                progressBar1.Value++;
            }
            MessageBox.Show("Instalação efetuada com sucesso!", "Aviso",
            MessageBoxButtons.OK, MessageBoxIcon.Information);
            lblStatus.Visible = false;
            progressBar1.Maximum = 0;
        }
    }
}

Being that it is displaying error in this line

DirectoryInfo di = new DirectoryInfo(diretorioFTP);

And the mistake in question is this:

System.NotSupportedException não foi manipulada
HResult=-2146233067
Message=Não há suporte para o formato do caminho dado.
Source=mscorlib
StackTrace: em System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
   em System.IO.DirectoryInfo.Init(String path, Boolean checkHost)
   em System.IO.DirectoryInfo..ctor(String path)
   em App_Install_Golden_Premium.frmInstala.btInstalar_Click(Object sender, EventArgs e) na D:\Fabio\Visual Studio\Projeto Golden Premium Download e instalacao\Instalador_golden_premium\App_Install_Golden_Premium\App_Install_Golden_Premium\frmInstala.cs:linha 78
   em System.Windows.Forms.Control.OnClick(EventArgs e)
   em System.Windows.Forms.Button.OnClick(EventArgs e)
   em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   em System.Windows.Forms.Control.WndProc(Message& m)
   em System.Windows.Forms.ButtonBase.WndProc(Message& m)
   em System.Windows.Forms.Button.WndProc(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.Run(Form mainForm)
   em App_Install_Golden_Premium.Program.Main() na D:\Fabio\Visual Studio\Projeto Golden Premium Download e instalacao\Instalador_golden_premium\App_Install_Golden_Premium\App_Install_Golden_Premium\Program.cs:linha 19
   em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   em System.Threading.ThreadHelper.ThreadStart()
InnerException: 
  • It will depend on the item that is marked, hence it fills with the directory of our ftp to which we have two different paths.

  • Directoryinfo di = new Directoryinfo(FTP directory);

  • From what I understand of your question, you want to know what is in the variable when the error appears.. Is this ? if this is the ftp path to which the executables are to be downloaded. If this is not the case I apologize for not understanding what you are asking.

  • the path is: "ftp://ftp.cetec.santamonicace.com.br/Producao/Executaveis/"

  • The DirectoryInfo does not accept FTP or HTTP paths, only local ones. You have to find another way to do what you want there.

  • I understand.... but on the whole what I’m trying to do is correct ?

  • In the panoramic view I have, your logic is correct. But you need to find another way to download the files and make your progress bar without using the DirectoryInfo. Here I gave an example of how to use the WebClient to download a file, take a look there

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.