This post explains how to upload a csv file into a stream on the server without uploading the file into a physical server location.
I have used a asp.net file upload control. This control exposes some properties which can be used to our advantage.
1. Content type – This returns the content type of the uploaded file. You can use this to make sure the content being uploaded is really an excel type file.
2. InputStream – This returns the stream object into which the contents of the file are loaded. This stream can be loded into a stream reader and you have the contents line by line.
'Code to upload csv file intp stream reader
Dim streamReader As System.IO.StreamReader
Dim fileUpload As System.Web.UI.WebControls.FileUpload = Me.FileUpload 'This control has to be added to the web form
Dim filePath As String = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName)
If Not filePath.Trim().Equals(String.Empty) Then
If fileUpload.PostedFile.ContentType.Equals("application/vnd.ms-excel") Then
If (fileUpload.PostedFile.InputStream.Length > 0) Then
If (fileUpload.PostedFile.FileName.ToLower().EndsWith(".csv")) Then
' Read and display the lines from the file until the end of the file is reached.
streamReader = New System.IO.StreamReader(fileUpload.PostedFile.InputStream)
streamReader.Close()
End If
End If
End If
End If
'----Code to read the stream reader line by line
While Not streamReader.EndOfStream
Dim strEmployeeIncreases As String = streamReader.ReadLine()
End While
'Make sure you close the stream reader after reading all the data using the following line of code to free up system
streamReader.Close()
'Also one more tip: If you want to skip to the top of the stream reader at any point of time, you can use
streamReader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin)