I am trying to save data to a csv file but want to ensure that the data that I am about to save isn't already pressent in the csv file. Because of this I want to read the file first and then save the data.
FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
FileStream reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamWriter sw = new StreamWriter(writer))
{
if (response.Datapoints.Count != 0)
{
foreach (var datapoint in response.Datapoints)
{
sb = new StringBuilder();
toBeSaved = new string[] { nameSpace, metric, instanceId, datapoint.Timestamp.ToString()};
foreach (string str in toBeSaved)
{
if (str == toBeSaved.Last())
{
sb.Append(str);
}
else
{
sb.Append(str);
sb.Append(",");
}
}
// here I get the error that the "Stream is not Readable"
using (StreamReader sr = new StreamReader(reader))
{
if (sr.ReadLine() != sb.ToString())
{ // only write the data if it is not already there in the file
sw.WriteLine(sb.ToString());
}
}
}