I've created a service worker which reads in serial port information and creates a .csv file to save the results to.
However, when i attempt to write to the file it says that the process cannot access the file, despite (from my knowledge) the file not being open, used by another external process or the filestream being open (i'm using System.IO.File.WriteAllLines()). What could the problem be?
static string InsturmentFile = $"{Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)}\\TestLogger\\";
public static void StartConnector()
{
Directory.CreateDirectory(InsturmentFile);
}
public static string FullFilePath(this string fileName)
{
return $"{InsturmentFile}\\{fileName}";
}
public static List<string> LoadFile(this string file)
{
if (!System.IO.File.Exists(file))
{
return new List<string>();
}
return System.IO.File.ReadAllLines(file).ToList();
}
public static List<InstrumentRawReading> ConvertToInstrumentRawReadingModel(this List<string> lines)
{
List<InstrumentRawReading> output = new List<InstrumentRawReading>();
foreach (string line in lines)
{
string[] cols = line.Split(',');
InstrumentRawReading u = new InstrumentRawReading();
string spacer = " ";
var now = DateTime.Now;
now = DateTime.Parse(cols[0]);
foreach (var reading in u.Readings)
{
reading.Name = cols[1];
}
output.Add(u);
}
return output;
}
public static void SaveReadingsLogToFile(this List<InstrumentRawReading> models, string fileName)
{
try
{
List<string> lines = new List<string>();
foreach (InstrumentRawReading u in models)
{
foreach (var rd in u.Readings)
{
lines.Add($"{rd.Time},{u.SerNo},{rd.Name},{rd.Rdg},{rd.Units}");
}
}
System.IO.File.WriteAllLines(fileName.FullFilePath(), lines);
}
catch (Exception ex)
{
Console.WriteLine("SaveReadingsLogToFile: " + ex.Message.ToString());
throw;
}
}
This is the full file creation class which i'm using the create the .csv file, it is being created and populated with one reading, however it seems that on the subsequent calls of the method it just stops working.