How to send selected data to an ftp server

Asked

Viewed 261 times

2

I am developing a project in c# and right now I have to select a line from a Datagridview that I created, create a text file with that data and send the created file to an ftp server. I’ve done some research, but I couldn’t find anything useful to me.If you want a code or a screenshot of my project I can make it available. This is the code of Datagridview:

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;

inserir a descrição da imagem aqui

UPDATE:

I’m using this code:

FtpWebRequest request = (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 mistake:

inserir a descrição da imagem aqui

  • Dude, FTP Server = File Transfer Protocol or Protocolo de Transferência de Arquivo. There is no way you can send data to the FTP server, you can send files, what would be your real need ? what you already have ready ?

  • I’ll edit the research to explain it better. I want to select the line and write the data on that line into a text file and send that text file to ftp. I already have the whole datagridview ready just missing the part to create the text file with the selected data and send to ftp

3 answers

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;
                    }
                }
            }
        }
    }
}
  • Thank you so much for your help, I’ll test

  • To be able to use this code I need it to send the selected line of datagridview

1


Step by step:

1- Checks for selected lines on the grid.

2- Traverse the selected lines one by one.

2.1 - Generates the text file, and writes to it with the class TextWriter running through each grid column, and separating the fields with a ;

2.2 - Close the object TextWriter

2.3 - Using the class FtpWebRequest next to a Stream to send the file to the FTP server.

Follows code:

    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();
            }
        }

    }
  • Thank you very much, I marked as reply

  • I have a question, the ftp://seuservidorftp.com/" how do I get my server like this in the example? My server looks like this : 123.12.321 is just paste over or I have to do something?

  • if 123.12.321 is your ip address... yes, just put ftp://123.12.321 (is missing a part to be a valid ip right) rs

  • 123.12.321 was an example. Thanks for the help

  • How do I insert the name of the created file into the columns "Transdocnumber"?

  • the file path is wrong... about the file name use the value of one of the columns, just do so: r.Cells[0].Value.ToString() and the file path on FTP should be: "ftp://123.321.123/" + arquivo.Name is missing bar to separate server from file name

  • This way FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://123.321.123/" + r.Cells[0].Value.ToString()); ?

  • cannot join the first 3 columns? You needed the name Dio file to be Transdocument + Transserial + Transdocnumber

  • give yes, just concatenate.... r.Cells[0].Value.ToString() + r.Cells[1].Value.ToString() + r.Cells[2].Value.ToString() you can also use the column name if you know... r.Cells["colunaX"].Value.ToString()

  • 1

    It worked, thank you very much

  • I can only ask one more question?

  • After sending I have to remove the sent line from datagridview and I am showing in datagridview so SqlCommand objcmd = new SqlCommand("SELECT TransDocument, TransSerial, TransDocNumber, PartyName, PartyLocalityID, TotalAmount, ShipToPostalCode FROM dbo.UXMenu WHERE Estado = 0", myConnection); and needed to update the selected line to change the state to 1 and so it leaves, how can I do this?

Show 8 more comments

0

This example shows how to load 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: https://msdn.microsoft.com/pt-br/library/ms229715(v=vs.110). aspx

  • If it helped, mark the answer, please. :)

Browser other questions tagged

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