Consider those two function. When I load file, everything is fine, but then, when I want to save changes, the file is still being locked. Where is the catch?
public static string Load(string loadPath = null)
{
string output;
string file = loadPath == null ? _defaultFile : (_defaultFile = loadPath);
try
{
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (!fileStream.CanRead)
{
Console.Out.Write("File is locked. Waiting for release ");
while (!fileStream.CanRead)
{
Console.Out.Write(".");
System.Threading.Thread.Sleep(2000);
}
}
using(var textReader = new StreamReader(fileStream))
{
var inputFileDescription =
new CsvFileDescription { SeparatorChar = ',', FirstLineHasColumnNames = true };
var cc = new CsvContext();
Students.AddRange(cc.Read<Student>(textReader, inputFileDescription));
output = "Database was successfully loaded.";
}
}
}
catch (Exception ex)
{
output = "Loading the provided database has failed.\n" + ex.Message;
}
return output;
}
public static string Save(string savePath = null)
{
string output;
string file = savePath == null ? _defaultFile : (_defaultFile = savePath);
try
{
using (var fileStream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
if (!fileStream.CanRead)
{
Console.Out.Write("File is locked. Waiting for release ");
while (!fileStream.CanRead)
{
Console.Out.Write(".");
System.Threading.Thread.Sleep(2000);
}
}
using (var textWriter = new StreamWriter(fileStream))
{
var outputFileDescription =
new CsvFileDescription { SeparatorChar = ',', FirstLineHasColumnNames = true };
var cc = new CsvContext();
cc.Write(Students, textWriter, outputFileDescription);
}
}
output = "Database was successfully saved to " + file;
}
catch (Exception ex)
{
output = "Saving to the provided database has failed.\n" + ex.Message;
}
return output;
}