jueves, 26 de octubre de 2023

C# ASP.NET - Subir archivos a carpeta compartida con credenciales.

 .ASPX

<%@ Page Title="Test Carpeta Compartida" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="TestCarpetaCompartida.aspx.cs" Inherits="LeaseOperWeb.Paginas.Administracion.TestCarpetaCompartida.TestCarpetaCompartida" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="HeaderContent" runat="server">

    <br /><asp:Label ID="Label1" runat="server" Text="TEST Carpeta Compartida"></asp:Label>

    <br />

    <br />

    <asp:FileUpload ID="fileUpload" runat="server" />

    <asp:Button ID="uploadButton" runat="server" Text="Subir archivo" OnClick="UploadFile" />

    <br />

    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

</asp:Content>



.CS

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LeaOperBussinesLayer.BussinesComponents.Administracion;

namespace LeaseOperWeb.Paginas.Administracion.TestCarpetaCompartida
{
    public partial class TestCarpetaCompartida : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void UploadFile(object sender, EventArgs e)
        {
            string urlCarpetaCompartida = new TesteoBc().GetURLCarpetaCompartida();
            string usernameCarpetaCompartida = new TesteoBc().GetUserCarpetaCompartida();
            string passwordCarpetaCompartida = new TesteoBc().GetPassCarpetaCompartida();


            if (!String.IsNullOrEmpty(urlCarpetaCompartida) || !String.IsNullOrEmpty(usernameCarpetaCompartida) ||
                !String.IsNullOrEmpty(passwordCarpetaCompartida))
            {
                if (fileUpload.HasFile)
                {
                    string fileName = Path.GetFileName(fileUpload.FileName);

                    string filePath =
                        Server.MapPath($"~/Uploads/{fileName}"); // Ruta temporal para guardar el archivo
                    string folderPath = Server.MapPath("~/Uploads");

                    if (!Directory.Exists(folderPath))
                        Directory.CreateDirectory(folderPath);

                    // Eliminar el archivo temporal en caso de que exista previamente
                    if (File.Exists(filePath))
                        File.Delete(filePath);

                    fileUpload.SaveAs(filePath);

                    // string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
                    string sharedFolderPath = urlCarpetaCompartida;

                    try
                    {
                        using (FileStream fileStream = File.OpenRead(filePath))
                            if (sharedFolderPath != null)
                                using (FileStream destination = File.Create(Path.Combine(sharedFolderPath, fileName)))
                                {
                                    fileStream.CopyTo(destination);
                                }

                        lblMessage.Text = @"Archivo subido exitosamente";
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Text = @"Ha ocurrido un error: " + ex.Message;
                    }
                }
            }
            else
            {
                lblMessage.Text =
                    @"Atención : Revisar paramétros 908-909-910 alguno de esos está vacío";
            }
        }
    }
}

C# ASP .NET - Subir archivos a un FTP

 Agregar control FILEUPLOAD


-.ASPX

<%@ Page Title="Test FTP" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="TestFTP.aspx.cs" Inherits="LeaseOperWeb.Paginas.Administracion.TestFTP.TestFTP" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="HeaderContent" runat="server">

    <br /><asp:Label ID="Label1" runat="server" Text="TEST FTP"></asp:Label>

    <br />

    <br />

    <asp:FileUpload ID="fileUpload" runat="server" />

    <asp:Button ID="uploadButton" runat="server" Text="Subir archivo" OnClick="UploadFile" />

    <br />

    <asp:Label ID="lblMessageConx" runat="server" Text=""></asp:Label>

    <br />

    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

</asp:Content>


.CS

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Security;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using LeaOperBussinesLayer.BussinesComponents.Administracion;


namespace LeaseOperWeb.Paginas.Administracion.TestFTP

{

    public partial class TestFTP : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {


        }


        public void TestConeccionFTP(string ftpServer, string ftpUsername, string ftpPassword)

        {

            /*Test de conexion*/

            try

            {

                // Crear una solicitud de conexión FTP.

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer);

                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

                request.Method = WebRequestMethods.Ftp.ListDirectory; // Puedes cambiar este método según tu necesidad.


                // Realizar la conexión y obtener la respuesta.

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();


                // Si llegamos aquí sin excepciones, la conexión fue exitosa.

                lblMessageConx.Text = "Conexión FTP exitosa.";

                response.Close();

            }

            catch (WebException ex)

            {

                lblMessageConx.Text = "Error de conexión FTP: " + ex.Message;

            }

            /*Fin test conexion*/


        }



        protected void UploadFile(object sender, EventArgs e)

        {

            string ftpServer = new TesteoBc().GetURLFTP(); // Reemplaza con tu servidor FTP                                 //ejemplo : ftp://192.168.1.99:21   (IP Y PUERTO)                                            

            string ftpUsername = new TesteoBc().GetUserFTP();// Reemplaza con tu nombre de usuario

            string ftpPassword = new TesteoBc().GetPassFTP(); // Reemplaza con tu contraseña

            string ssl = new TesteoBc().GetSSl(); //reemplaza con ssl  true o false


            if (!String.IsNullOrEmpty(ftpServer) || !String.IsNullOrEmpty(ftpUsername) ||

                !String.IsNullOrEmpty(ftpPassword) || !String.IsNullOrEmpty(ftpUsername))

            {


                TestConeccionFTP(ftpServer, ftpUsername, ftpPassword);


                if (fileUpload.HasFile)

                {

                    string fileName = Path.GetFileName(fileUpload.FileName);


                    try

                    {

                        string filePath =

                            Server.MapPath($"~/Uploads/{fileName}"); // Ruta temporal para guardar el archivo

                        string folderPath = Server.MapPath("~/Uploads");


                        if (!Directory.Exists(folderPath))

                            Directory.CreateDirectory(folderPath);


                        // Eliminar el archivo temporal en caso de que exista previamente

                        if (File.Exists(filePath))

                            File.Delete(filePath);



                        fileUpload.SaveAs(filePath);


                        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + "/" + fileName);

                        request.Method = WebRequestMethods.Ftp.UploadFile;

                        request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);


                        // Habilitar SSL implícito

                        if (ssl.Trim().ToLower() == "true")

                            request.EnableSsl = true;


                        using (FileStream fileStream = File.OpenRead(filePath))

                        using (Stream requestStream = request.GetRequestStream())

                        {

                            byte[] buffer = new byte[1024];

                            int bytesRead;


                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)

                            {

                                requestStream.Write(buffer, 0, bytesRead);

                            }

                        }


                        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                        lblMessage.Text =

                            $"Archivo {fileName} cargado con éxito. Código de respuesta: {response.StatusDescription}";


                        // Eliminar el archivo temporal

                        if (File.Exists(filePath))

                            File.Delete(filePath);


                        response.Close();

                    }

                    catch (Exception ex)

                    {

                        lblMessage.Text = $"Error al cargar el archivo: {ex.Message}";

                        // Eliminar el archivo temporal


                    }

                }

                else

                {

                    lblMessage.Text =

                        "Por favor, selecciona un archivo para cargar o verifica que el archivo no esté vacío";

                }

            }

            else

            {

                lblMessage.Text =

                    @"Atención : Revisar paramétros 904-905-906 alguno de esos está vacío";

            }

        }



    }

}