Search code examples
c#fileurl-rewritingtemp

How to rewrite txt file-why my code doesn't work


I want rewrite my txt file(I need delete lines). I use this code:

 string cesta3 = cesta + "database.txt";
 string file = new StreamReader(cesta3).ReadToEnd();

 var linesToKeep = File.ReadLines(cesta3)
    .Where(l => l != "Meno: " + textBox1.Text + " PN " + textBox2.Text);       

But I don't know how to save my file with that same name.I try this:

 File.WriteAllLines(cesta3, linesToKeep); // <== exception

 var tempFile = Path.GetTempFileName();
 File.Move(tempFile + ".txt", cesta3);

But it throws exception:

Additional information: Access to the path "'C:\Users\Lenovo\documents\visual studio 2015\Projects\attendancer\attendancer\bin\Debug\database.txt‌​' is denied."

How can I do ?


Solution

  • This line of code locks the file and prevent it from moving: string file = new StreamReader(cesta3).ReadToEnd();.

    Fix:

    • you can properly close StreamReader after reading file text from it with using
    • alternatively since there is nothing in the sample using that StreamReader or result of ReadToEnd (file variable) you can simply remove that line.

    Side note: File.Move will throw more exceptions after you are done with the first one as source file is unlikely to exist - I'm not sure what you were trying to do with that call.