I’m trying to make a simple logger for my Netduino Plus. I’ve looked at heaps of different examples and looked over the forums for days but haven’t found any that suit. So I’m posting for help.
I’m trying to make a class that has three functions.
Log.Write(string text)
Log.Read()
Log.Trim(int lines)
Below is what I’ve got so far but it’s obviously bogus. I think I’m on the right track but I might be way off. I think I could pull it off if it wasn’t such a large file that I can’t read it all into memory. Because I’m not using a real time clock, I don’t have a way to purge the file except from by line number. I really need the log to always stay at 200 lines long. I want Log.Trim to delete any lines past 200 and Log.Write to add to the file at the beginning. And to top it all off I need Log.Read to return it to a single string one line at a time so I can view it on the webserver. Without using all the memory.
Thanks in Advance.
using System; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware; using SecretLabs.NETMF.Hardware.NetduinoPlus; using System.IO; namespace WebserverTest { class Log { public static string read() { int counter = 0; string line; System.IO.StreamReader file = new System.IO.StreamReader(@"\SD\Log.txt"); while ((line = file.ReadLine()) != null) { System.Console.WriteLine(line); //I know i've got this wrong but i'm a noob! counter++; } file.Close(); Debug.Print("There were " + counter.ToString() + " lines read"); return line; } public static void Write(string text) { Trim(200); using (var filestream = new FileStream(@"\SD\Log.txt", FileMode.Append)) { StreamWriter sw = new StreamWriter(filestream); sw.BaseStream.Seek(0, SeekOrigin.Begin); sw.Write(" File Write Operation Starts : \n"); sw.WriteLine(" First Line : Data is first line \n"); sw.WriteLine(" This is next line in the text file. \n "); sw.Flush(); sw.Close(); } } public static void Trim(int lines) { string line = null; int line_number = 0; int line_to_delete = lines; using (StreamReader reader = new StreamReader(@"\SD\Log.txt")) { using (StreamWriter writer = new StreamWriter(@"\SD\Temp.txt")) { while ((line = reader.ReadLine()) != null) { line_number++; if (line_number == line_to_delete) continue; writer.WriteLine(line); } } } SetUp.confirm(); File.Delete(@"\SD\Log.txt"); File.Move(@"\SD\Temp.txt", @"\SD\Log.txt"); } } }