I'm looking for a way to read only the last line of a json file on the server in an efficient way using C#. There is one way I can think of is first download the file, save file to local drive, and then using File.Readlines(path).Last()
to read the last line. However the file can be quite big, and the download time can be slow. Is there anyway that I can read the last line without having to download it first?
Asked
Active
Viewed 306 times
-1

madlink
- 9
- 5
-
2Isn't the last line of a JSON file going to be `}`? Can you explain what problem you're trying to solve here? – Daniel Mann Mar 21 '19 at 14:36
-
You will need to still to download the file, but you can use the seek function from the FileStream object to read backwards through the file. This link should help https://stackoverflow.com/questions/5208592/reading-parts-of-large-files-from-drive – vscoder Mar 21 '19 at 14:36
-
1Unless you can convince the server to send you only the last bit of a file, you'll need to download the whole thing. – Flydog57 Mar 21 '19 at 14:39
-
@DanielMann No, it's only when you format the file, it will be that. Otherwise it can be {something} as a really long line. – madlink Mar 21 '19 at 14:39
-
1you don't need to save the json as a file, download into a memorystream and read from that using a streamreader – D.J. Mar 21 '19 at 14:40
-
What access do you have on the server http,fileshare, etc. Another option might be remote execute a tail like command on windows to avoid the download time. powershell -command "& {Get-Content *filename* | Select-Object -last *n*} > last_line.txt – Jason Phillips Mar 21 '19 at 14:43
-
What software is hosting the file? A standard webserver, or some custom website, or webservice. If it is a web service/api/method, and you have control over it, then you should just provide a new method to send only the required content of the file to the client – Vikhram Mar 21 '19 at 14:54
-
The file is hosted in an ftp server. – madlink Mar 21 '19 at 14:58
1 Answers
0
Thanks to D.J's suggestion! I manage to read it without downloading the whole file. I don't know about the performance though.
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream)) {
var last = "";
while (reader.EndOfStream == false) {
last = reader.ReadLine();
}
reader.Close();
}

madlink
- 9
- 5