TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
How to Read the Data from CSV File in ASP.NET
Sarath Kumar
Dec 12
2014
Code
23.3
k
0
2
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
Code
<asp:FileUpload ID=
"fpContacts"
runat=
"server"
/>
<asp:Button ID=
"btnUpload"
runat=
"server"
Text=
"Upload"
OnClick=
"btnUpload_Click"
/></p>
Here we need to add a new folder to the solution, why because, sometimes it will takes the fake file path. it is better to save the file and read data.
In .cs page, write the following code.
protected
void
btnUpload_Click(
object
sender, EventArgs e)
{
if
(fpContacts.HasFile)
{
string
spath = Server.MapPath(
"~/upload"
);
string
csv_file_path = spath +
"\\"
+ fpContacts.FileName;
fpContacts.SaveAs(csv_file_path);
DataTable csvData = GetDataTableFromCSVFile(csv_file_path);
}
}
public
DataTable GetDataTableFromCSVFile(
string
csv_file_path)
{
DataTable csvData =
new
DataTable();
try
{
using
(TextFieldParser csvReader =
new
TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(
new
string
[] {
","
});
csvReader.HasFieldsEnclosedInQuotes =
true
;
//read column names
string
[] colFields = csvReader.ReadFields();
foreach
(
string
column
in
colFields)
{
DataColumn datecolumn =
new
DataColumn(column);
datecolumn.AllowDBNull =
true
;
csvData.Columns.Add(datecolumn);
}
while
(!csvReader.EndOfData)
{
string
[] fieldData = csvReader.ReadFields();
ContactEntity CEntity =
new
ContactEntity();
B2B_BillsData BData =
new
B2B_BillsData();
CEntity.ContactName = fieldData[0];
CEntity.Email = fieldData[1];
CEntity.Mobile = fieldData[2];
CEntity.GroupId = ddlGroup.SelectedIndex;
CEntity.UserId = userid;
if
(BData.InsertNewContact(CEntity) ==
true
)
{
lblMsg.ForeColor = Color.Green;
lblMsg.Text =
"Contact Saved successfully"
;
}
csvData.Rows.Add(fieldData);
}
}
}
catch
(Exception ex)
{
//MessageBox.Show(ex.Message);
}
return
csvData;
}
Happy coding........
CSV file
file upload control
read the data from CSV file in ASP.NET