How to send selected data to an ftp server

2

I am developing a project in C # and at this point I have to select a row from a DataGridView that I created, create a text file with that data and send the file created to an ftp server. I already did a search, but I could not find anything that was useful to me. If you want some code or some screenshot of my project I can make it available. This is the DataGridView code:

SqlConnection myConnection = new SqlConnection(@"Data source = **** ; Database=**** ; User Id=****; Password=*****");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT TransDocument, TransSerial, TransDocNumber, PartyName, PartyLocalityID, TotalAmount, ShipToPostalCode FROM dbo.UXMenu WHERE Estado = 0", myConnection);
objcmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewEnviarDados.DataSource = dt;
dataGridViewEnviarDados.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

UPDATE:

I'musingthiscode:

FtpWebRequestrequest=(FtpWebRequest)WebRequest.Create("ftp://123.321.123" + arquivo.Name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("usuario", "password");
StreamReader sourceStream = new StreamReader(arquivo.FullName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
MessageBox.Show("Arquivo " + arquivo.Name + " foi enviado com sucesso. " + response.StatusDescription);
response.Close();'  

But I have this error:

    
asked by anonymous 24.08.2017 / 16:40

3 answers

1

Walkthrough:

1- Checks if there are rows selected in the grid.

2- Browse the selected lines one by one.

2.1 - Generate the text file, and write in it with the class TextWriter going through each column of the grid, and separating the fields with a ;

2.2 - Close the object TextWriter

2.3 - Uses the class FtpWebRequest together with a Stream to send the file to the FTP server.

Follow the code below:

    private void buttonEnviar_Click(object sender, EventArgs e)
    {
        if (dataGridView1.SelectedRows.Count > 0)
        {
            foreach (DataGridViewRow r in dataGridView1.SelectedRows)
            {
                FileInfo arquivo = new FileInfo("C:\arquivoDeTexto_"+r.Index+".txt");

                using (TextWriter tw = new StreamWriter(arquivo.FullName, false, Encoding.Default))
                {
                    foreach (DataGridViewColumn c in dataGridView1.Columns)
                    {
                        tw.Write(r.Cells[c.Name].Value.ToString()+";");
                    }

                    tw.Close();
                }

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://seuservidorftp.com/"+ arquivo.Name);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                request.Credentials = new NetworkCredential("usuario", "senha");

                StreamReader sourceStream = new StreamReader(arquivo.FullName);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

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

                MessageBox.Show("Arquivo " + arquivo.Name + " foi enviado com sucesso. " + response.StatusDescription);

                response.Close();
            }
        }

    }
    
24.08.2017 / 18:53
1
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

namespace Examples.System.Net
{
    public class EnvioFtp
    {
        /// <summary>
        /// Atributo para lib
        /// </summary>
        private FtpWebRequest FtpClient { get; set; }
        /// <summary>
        /// Atribui valores iniciais para envio e conexão
        /// </summary>
        private void ConectaFtp()
        {
            this.FtpClient = (FtpWebRequest)WebRequest.Create("ftp://endereco.com/teste.txt");
            this.FtpClient.Credentials = new NetworkCredential("usuario", "senha");
        }

        /// <summary>
        /// Realiza envio, utilizando o atributo já iniciado(FtpClient)
        /// </summary>
        public void EnviaProjetoFtp()
        {

            this.ConectaFtp();
            FileInfo arquivoInfo = new FileInfo("teste.txt");
            this.FtpClient.Method = WebRequestMethods.Ftp.UploadFile;
            this.FtpClient.UseBinary = true;
            this.FtpClient.ContentLength = arquivoInfo.Length;

            using (FileStream fs = arquivoInfo.OpenRead())
            {
                byte[] buffer = new byte[2048];
                int bytesSent = 0;
                int bytes = 0;

                using (Stream stream = this.FtpClient.GetRequestStream())
                {
                    while (bytesSent < arquivoInfo.Length)
                    {
                        bytes = fs.Read(buffer, 0, buffer.Length);
                        stream.Write(buffer, 0, bytes);
                        bytesSent += bytes;
                    }
                }
            }
        }
    }
}
    
24.08.2017 / 17:40
0

This example shows how to upload a file to an FTP server. Example C #

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","[email protected]");

            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader("testfile.txt");
            byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

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

            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

            response.Close();
            }
        }
    }
}

Source: link

    
24.08.2017 / 16:55