Search code examples
csvvbscriptasp-classicreadfile

Read CSV file using classic ASP/VB script


I want to read the values in the following CSV file in classic ASP .

enter image description here

For that first I'm uploading the file and storing it in the server. Then I'm reading that file and trying to store the values of each column in variables using a loop and then pass this variables to some method. I have written the code but seems to have issue in looping the values. The code seems to store the file and open it properly but fails to loop values in it to the variables.

Here is my code:

    <HTML>
<HEAD>
<!--#include file="clsUpload.asp"-->
</HEAD>
<BODY>
<FORM ACTION = "clsUploadTEST.asp" ENCTYPE="multipart/form-data" METHOD="POST">
Demo Input: <INPUT NAME = "Demo"></INPUT><P>
File Name: <INPUT TYPE=FILE NAME="txtFile"><P>
<INPUT TYPE = "SUBMIT" NAME="cmdSubmit" VALUE="SUBMIT">
</FORM><P>
<%

Dim lineData
Dim  code
Dim name
Dim mail
Dim id
Dim price
Dim amount
Dim i As Integer
i = 0
set o = new clsUpload
if o.Exists("cmdSubmit") then

'get client file name without path
sFileSplit = split(o.FileNameOf("txtFile"), "\")
sFile = sFileSplit(Ubound(sFileSplit))

o.FileInputName = "txtFile"
o.FileFullPath = Server.MapPath(".") & "\" & sFile
o.save
'saving the files
 if o.Error = "" then
    response.write "Success. File saved to  " & o.FileFullPath & ". Demo Input = " & o.ValueOf("Demo")
 else
    response.write "Failed due to the following error: " & o.Error
 end if

end if
'reading the file
Set fso = Server.CreateObject("Scripting.FileSystemObject") 
set fs = fso.OpenTextFile(Server.MapPath("customer.csv"), 1, true)    
Do Until fs.AtEndOfStream 
    lineData = fs.ReadLine
     ReDim MyArray(0)
     MyArray = Split(lineData , ",")
     code= MyArray(0)
     name=MyArray(1)
     mail=MyArray(2)
     id=MyArray(3)
     price=MyArray(4)
     amount=MyArray(5)
    ' pass this value to some method like.. addtoracleDB(code,name......etc)   
    Response.Write code
    i=i+1
Loop 

fs.close: set fs = nothing 
set o = nothing
%>
</BODY>
</HTML>

Can anyone please help me with this ? Can anyone help me know where i made the mistake ? the other solutions that I found on stackoverflow was not working for me and some online solution with third party components also didnt work for me . Its a kind of a challenge as its a legacy technology


Solution

  • It looks like you are reading the content of the line into lineData:

    lineData = fs.ReadLine
    

    But then you are using strLine instead of lineData:

    MyArray = Split(strLine, ",")
    

    I think the following should work:

    MyArray = Split(lineData, ",")
    

    MyArray doesn't seem to be declared anywhere though, you should add it to your Dim statements at the top of your code block:

    Dim MyArray
    

    Then, remove the ReDim statement.