C# Question

the process cannot access the file, using filewriter

Trying to check if the file is empty or not, and then write something like "the text is empty" into the document.

But whenever I do get the


the process cannot access the file because it is being used by another process


even though I'm closing the file after the write.

What am I missing here?

StreamWriter myWriter1 = new StreamWriter(resultpath);
List<string> a = File.ReadAllLines(path).ToList();
List<string> b = File.ReadAllLines(newPath).ToList();

foreach (string s in a)
{
Console.WriteLine(s);
if (!b.Contains(s))
{
myWriter1.WriteLine(s);
myWriter1.Close();
}
else
{
continue;
}
}

string[] resultfile = File.ReadAllLines(resultpath);
if (resultfile == null || resultfile.Length == 0)
{
myWriter1.WriteLine("Der er ikke nogen udmeldinger idag", true);
}
myWriter1.Close();

Answer

Try this code. You were closing the StreamWriter on each line that is in the 2 analized files,but if there is no coincidence, you never close it.

using (var myWriter1 = new StreamWriter(resultpath, true))
{
    List<string> a = File.ReadAllLines(path).ToList();
    List<string> b = File.ReadAllLines(newPath).ToList();


    int coincidences=0;
    foreach (string s in a)
    {
        Console.WriteLine(s);


        if (!b.Contains(s))
        {
            myWriter1.WriteLine(s);
            coincidences++;
        }
    }

    if (coincidences == 0)
    {
         myWriter1.WriteLine("Der er ikke nogen udmeldinger idag", true);
    }

}

Also,note that for IDisposable objects it's better to enclose it in a using clause,as it disposes all the resources when finished.