Solved

How to send a csv file to a ftp site

Posted on 2008-06-18
6
714 Views
Last Modified: 2013-12-16
I've got a 500kb csv file with around 12000 lines and 4 columns: ID, First Name, Last Name, DOB and Location (which is just three letters). I would like to know how can I send this csv file to a ftp site using C# Visual Studio 2005 ASP 2.0
0
Comment
Question by:soliveira
  • 4
  • 2
6 Comments
 
LVL 6

Expert Comment

by:rafayali
ID: 21818398
Here is some sample code from a ftp project that I was working on. It has some methods to list directories, create directories and delete directories. If you can figure out how to upload a file from the sample I have pasted, thats fine. Other wise let me know and I will show you (as a code example) how to upload a file using FTP in .NET.

Here is the sample code. It should be pretty straight forward to figure out:

Have a look at two posts below: First post is the class file, second is how class is used in the default.aspx page.
Imports Microsoft.VisualBasic

Imports System.IO

Imports System.Net
 
 

Public Class ftpclientcode

    Protected myftprequest As FtpWebRequest

    Protected myftpresponse As FtpWebResponse

    Private _myserver As String

    Private _myuser As String

    Private _mypw As String
 

    Public Sub New(ByVal myserver As String, ByVal myuser As String, ByVal mypw As String)

        _myserver = myserver

        _myuser = myuser

        _mypw = mypw

        myftprequest = WebRequest.Create(_myserver)

        myftprequest.Credentials = New NetworkCredential(_myuser, _mypw)
 

    End Sub

    
 

    Public Function ListFiles() As Stream

        myftprequest.Method = WebRequestMethods.Ftp.ListDirectory

        myftpresponse = myftprequest.GetResponse()

        Return myftpresponse.GetResponseStream()
 

    End Function
 

    Public Sub MakeDirectory(ByVal mydirname As String)
 

        myftprequest.Method = WebRequestMethods.Ftp.MakeDirectory

        myftpresponse = myftprequest.GetResponse()
 

    End Sub
 

    Public Shared Sub Close()

        ' myftpresponse.Close()
 

    End Sub
 

    Public Sub DeleteDirectory(ByVal mydirname As String)

        myftprequest.Method = WebRequestMethods.Ftp.RemoveDirectory

        myftpresponse = myftprequest.GetResponse()
 

    End Sub
 
 

End Class

Open in new window

0
 
LVL 6

Expert Comment

by:rafayali
ID: 21818408
Following shows usage of the above class file. The class file is named ftpclientcode.
'The following is code to delete directory on FTP server. It executes when button1 is clicked.
 

Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        Panel4.Visible = False

        Panel1.Visible = True

        Panel2.Visible = True
 

        Dim myftp As New ftpclientcode("ftp://" & servername & "/" & TextBox2.Text, myusername, mypassword)

        Try

            myftp.DeleteDirectory(TextBox2.Text)
 

        Catch ex As Exception

            Response.Write(ex.Message.ToString())
 

        End Try

        Page_Load(sender, e)

    End Sub
 
 

'Following is code to create directory on FTP Server
 

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles createbutton.Click

        Panel3.Visible = False

        Panel1.Visible = True

        Panel2.Visible = True
 
 

        Dim myftp As New ftpclientcode("ftp://" & servername & "/" & TextBox1.Text, myusername, mypassword)

        Try

            myftp.MakeDirectory(TextBox1.Text)

            Page_Load(sender, e)
 
 
 
 

        Catch ex As Exception

            Response.Write(ex.Message.ToString())
 
 

        Finally

            'myftp.Close()

        End Try
 

'The following code executes on Page_Load and instantiates ftpclientcode class and logs into the FTP server and lists all the files on FTP server
 

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 

       
 

        Dim myftp As New ftpclientcode("ftp://" & servername, myusername, mypassword)
 

        Label1.Text = ""

        Dim datastream As Stream = myftp.ListFiles()

        Dim reader As New StreamReader(datastream)

        While Not reader.EndOfStream

            'Response.Write(reader.ReadLine() & "<br/>")

            Label1.Text = Label1.Text & "&nbsp;&nbsp;ª&nbsp;&nbsp;&nbsp;" & reader.ReadLine() & "<br/>"
 

        End While

        'myftp.Close()
 
 
 
 

    End Sub
 
 

'Following are class level variables declared (outside of any subs or function routines)
 

Private servername As String = "localhost"

    Private myusername As String = "rafayali"

    Private mypassword As String = "29jan1980"

Open in new window

0
 
LVL 6

Expert Comment

by:rafayali
ID: 21818451
Here is soem sample code I wrote up quick. Test it and let me know if it worked. I havent had the chance to test it.

Dim myRequest as FtpWebRequest=WebRequest.Create("ftp://servername/filename_to_upload")
myRequest.method=WebRequestMethods.Ftp.UploadFile
myRequest.Credentials=New NetworkCredential(username,password)
Dim myStream as filestream=file.openRead("d:\rafay\1.csv")
Dim myDataBuffer(myStream.length) as byte
myStream.Read(myDataBuffer,0,myDataBuffer.length)
myStream.Close()
myStream=nothing
myRequest.GetRequestStream().write(myDataBuffer,0,myDataBuffer.length)
myRequest=nothing

Place this code in the button click event, or any other event handler
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:soliveira
ID: 21818486
Hi Rafayali,

I couldn't figure out from your sample do what I am after. I would like to get a csv file from C: of my machine and place it on the root of the ftp site. I am doing this for a XML file already (see attcahe code)but if I use the same code for the csv file ir doesn't work.
private void UploadXMLFile()

        {

            Stream Stream = null;

            FileInfo FileInf = new FileInfo(oAEVTI_CSI_XML.XMLFileName);
 

            string uri = "ftp://10.250.203.5/" + FileInf.Name;

            FtpWebRequest ReqFTP;

            ReqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

            ReqFTP.Credentials = new NetworkCredential("zzz", "xxx");

            ReqFTP.KeepAlive = false;

            ReqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            ReqFTP.UseBinary = true;
 

            ReqFTP.ContentLength = FileInf.Length;
 

            int BuffLength = 2048;

            byte[] Buff = new byte[2048];

            int ContentLen;
 

            FileStream FS = FileInf.OpenRead();

            long FileLength = FileInf.Length;

            long Done = 0;

            long DoneAct = 0;
 

            try

            {
 

                Stream = ReqFTP.GetRequestStream();

                ContentLen = FS.Read(Buff, 0, BuffLength);

                DoneAct += ContentLen;

                while (ContentLen != 0)

                {

                    Stream.Write(Buff, 0, ContentLen);

                    ContentLen = FS.Read(Buff, 0, BuffLength);

                    DoneAct += ContentLen;

                    if (Done < (DoneAct * 100 * 100 / FileLength))

                    {

                        Done = (DoneAct * 100 * 100 / FileLength);

                        //Console.WriteLine(((double)(Done / 100.00)).ToString("00.00") + " % Complete..");

                    }

                }

            }

            finally

            {

                if (Stream != null)

                {

                    Stream.Close();

                }

                if (FS != null)

                {

                    FS.Close();

                }

            }

        }

Open in new window

0
 
LVL 6

Accepted Solution

by:
rafayali earned 500 total points
ID: 21818561
Hi,

I tried your code above by using a csv file (created from excel export as csv). It uploaded fine when I changed the name in FileInf to the csv file like this

FileInfo FileInf = new FileInfo("d:\\ecubicle\\resources.csv");

It worked on my end.

What exactly is the error message that you receive when trying to upload csv. It is fairly odd that problems would surface for one file type when it works for another file type.
0
 

Author Comment

by:soliveira
ID: 21818629
That is ture rafa,

My problem was that I was searching for the last file in ftp site but It comes at first.
thank you very much for you help and sorry for that.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
I need help using System.Web.HttpUtility.HtmlEncode in my VB.Net application 3 54
Linq Help 1 35
Tool Box 2 34
Turn on intranet settings 1 36
A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now