Skip to content

Instantly share code, notes, and snippets.

@afreeland
Created March 25, 2013 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afreeland/5237760 to your computer and use it in GitHub Desktop.
Save afreeland/5237760 to your computer and use it in GitHub Desktop.
C#: Import CSV file and get CSV headers
public JsonResult ImportCSV(HttpPostedFileBase file)
{
if (file == null)
return Json(new JSON.Result() { Status = JSON.Result.StatusEnum.Failed, DisplayMessage = "No Upload File Present" });
if (file.ContentLength == 0)
return Json(new JSON.Result() { Status = JSON.Result.StatusEnum.Failed, DisplayMessage = "File does not have Content Length" });
var delimiter = ",";
var lineNumber = 0;
var splitExpression = new Regex(@"(" + delimiter + @")(?=(?:[^""]|""[^""]*"")*$)");
string[] headers = null;
using (var reader = new StreamReader(file.InputStream))
{
string line = null;
line = reader.ReadLine();
headers = splitExpression.Split(line).Where(x => x != delimiter).ToArray();
}
return Json(new JSON.Result() { Status = JSON.Result.StatusEnum.Success, ReturnedData = JSON.Serialize(headers), DisplayMessage = "Headers" });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment