public ActionResult <string> Open(string filePath) { //Check for valid filepath if (System.IO.File.Exists(filePath) == false) { var message = $"No file exists on disk at {filePath}"; return(NotFound(message)); } //Check for file extension ends with one of the following //.json .txt or .clef //Don't want to attempt to any old file type var extension = Path.GetExtension(filePath); if (extension != ".txt" && extension != ".json" && extension != ".clef") { var message = $"The file {filePath} is not a compatible log file. Can only open .json, .txt or .clef files"; return(BadRequest(message)); } //Lets check file is valid JSON & not a text document on your upcoming novel var firstLine = System.IO.File.ReadLines(filePath).First(); if (firstLine.IsValidJson() == false) { var message = $"The file {filePath} does not contain valid JSON on line one"; return(BadRequest(message)); } //We will skip over/ignore invalid/malformed log lines var logs = _logParser.ReadLogs(filePath); return($"Log contains {logs.Count}"); }
public ActionResult <string> Open(string filePath) { //Check for valid filepath if (System.IO.File.Exists(filePath) == false) { var message = $"No file exists on disk at {filePath}"; return(NotFound(message)); } //Lets check file is valid JSON & not a text document on your upcoming novel string?firstLine; using (var s = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(s)) { firstLine = sr.ReadLine(); } if (firstLine.IsValidJson() == false) { var message = $"The file {filePath} does not contain valid JSON on line one"; return(BadRequest(message)); } //We will skip over/ignore invalid/malformed log lines try { var logs = _logParser.ReadLogs(filePath); return($"Log contains {logs.Count}"); } catch (InvalidDataException ex) { // Can be InvalidDataExcpetion or JsonFormatterException // Such as 'The data on line 1 does not include the required @t field' return(BadRequest($"There was a problem reading the JSON. {ex.Message}")); } }