public ActionResult ImageUpload(HttpPostedFileBase FileUpload)
{
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/EventImages"));
FileInfo[] file = dir.GetFiles();
int x = file.Length;
x++;
if (ModelState.IsValid)
{
if (FileUpload.ContentLength > 0 && FileUpload.ContentType == "image/jpeg")
{
string fileExtention = Path.GetExtension(FileUpload.FileName);
string fileName = Convert.ToString(x) + fileExtention;
string path = Path.Combine(Server.MapPath("~/EventImages"), fileName);
string dbPath = "~/EventImages/"+ fileName;
try
{
person = new Person();
FileUpload.SaveAs(path);
dt = ProcessCSV(path);
ViewData["Feedback"] = "Upload Complete!";
}
catch (Exception ex)
{
ViewData["Feedback"] = ex.Message;
}
}
}
}
private static DataTable ProcessCSV(string fileName)
{
string Feedback = string.Empty;
string line = string.Empty;
string[] strArray;
DataTable dt = new DataTable();
DataRow row;
Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
StreamReader sr = new StreamReader(fileName);
line = sr.ReadLine();
strArray = r.Split(line);
Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));
while ((line = sr.ReadLine()) != null)
{
row = dt.NewRow();
row.ItemArray = r.Split(line);
dt.Rows.Add(row);
}
sr.Dispose();
return dt;
}
This is all about Code lovers, who are developing apps using Microsoft .NET technology
Tuesday, 29 May 2012
Uploading CSV file using MVC 3 in C#
Here is code for file upload in MVC
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment