Solved

How to send a csv file to a ftp site

Posted on 2008-06-18
6
712 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:soliveira
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Normally the drop down box control found in the .Net framework tools is able to select just one data and value at a time, which is displayed on the text area.   But what if you want to have multiple values to be selected in the drop down box? As …
Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

771 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

10 Experts available now in Live!

Get 1:1 Help Now