public static ulong readVolumeFile(out UInt32 dongleID) { //read only UInt32 _dongleID = 0; var readData = default(byte[]); ulong tmpVolume = 0; try { FileStream logFileStream = new FileStream(tonerVolumeFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (StreamReader sr = new StreamReader(logFileStream)) { using (var memstream = new MemoryStream()) { sr.BaseStream.CopyTo(memstream); readData = memstream.ToArray(); } // Clean up sr.Close(); logFileStream.Close(); } if (readData.Length != 0) { tmpVolume = BlowFishImpl.decodeVolumeData(readData, out _dongleID); } } catch (Exception exp) { Trace.WriteLine("Read ink file got exception " + exp.Message); } dongleID = _dongleID; return(tmpVolume); }
public static bool addVolumeToFile(UInt32 intToneVolume, UInt32 dongleIDFromFile, bool bReadFile) { bool bWritedFile = false; try {//1. check file existed //2. read data inside //3. if read data is empty, write volume read from tag //4. if read data not empty, add the volume read from tag, if over max, set to max ulong tmpVolume = readVolumeFile(out dongleID); if (bReadFile && (dongleIDFromFile != dongleID)) { Trace.WriteLine("*** Dongle ID did not matched"); return(false); } Trace.Write("read Dongle ID " + dongleID); byte[] defaultData = BlowFishImpl.encodeVolumeData((ulong)intToneVolume * 1000000000, dongleID); if (!File.Exists(tonerVolumeFile)) {//create file first bWritedFile = false; using (StreamWriter sw = File.CreateText(tonerVolumeFile)) { sw.WriteLine(""); sw.Close(); } for (int i = 0; i < 5 && !bWritedFile; i++) { bWritedFile = writeByteToFile(defaultData); if (bWritedFile) { Trace.WriteLine("Ink file not found, write " + Encoding.Default.GetString(defaultData)); return(true); } } return(false); } if (tmpVolume == 0) {//empty file bWritedFile = false; for (int i = 0; i < 5 && !bWritedFile; i++) { bWritedFile = writeByteToFile(defaultData); if (bWritedFile) { Trace.WriteLine("Ink file empty, add " + intToneVolume.ToString() + "L"); return(true); } } } else { DateTime aTime = DateTime.Now; Trace.Write(aTime.ToString("MM/dd/yyyy HH:mm:ss: ")); currentTonerVolume = tmpVolume + (ulong)intToneVolume * 1000000000; Trace.Write("Ink file read " + currentTonerVolume.ToString() + ", "); if (currentTonerVolume > tonerMAXVolume) { currentTonerVolume = tonerMAXVolume; } bWritedFile = false; for (int i = 0; i < 5 && !bWritedFile; i++) { bWritedFile = writeByteToFile(BlowFishImpl.encodeVolumeData(currentTonerVolume, dongleID)); if (bWritedFile) { Trace.WriteLine("Ink file read, add " + currentTonerVolume.ToString() + "L"); return(true); } } } } catch (Exception exp) { Trace.WriteLine("Get Exception " + exp.Message); } return(false); }