Solved

How to send a csv file to a ftp site

Posted on 2008-06-18
6
718 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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

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.

Question has a verified solution.

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

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

777 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