Solved

How to send a csv file to a ftp site

Posted on 2008-06-18
6
731 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

691 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