1
votes

I'm getting error when I'm overwriting the file. And if it is still working can't find to way for close file. Can someone help me please ?

        if (System.IO.File.Exists(Server.MapPath("/html/" + htmlname)))
        {
            System.IO.File.Delete(Server.MapPath("/html/" + htmlname));

            System.IO.File.WriteAllText(Server.MapPath("/html/" + htmlname), mailbody);

        }
        else
        {
            System.IO.File.WriteAllText(Server.MapPath("/html/" + htmlname), mailbody);
        }
1
In my experience the static File IO methods aren't good about disposing of file handles. I would change to using FileStream and managing the resources yourself; you may be stepping on your own foot. - Jeff
@Jeff would you/we implement file writing better or different than what WriteAllText() does? - Adriano Repetti
@Seration you should first find all places you write to that file. Did you miss a Close()/Dispose()? Is there something asynchronous? Without more context you'll just receive 10.000 suggestions (and if you check them all you may even pick right one...) - Adriano Repetti
@Adriano The problem is when i write "file." there is no close() or dispose() option. So i really ve no idea about missing someting - Seration
If you write using that static methods you don't need to close it (they do it). You have to close it when you have a stream (for example from File.Open). You have check if you use it in an asynchronous manner too (for example you write and read in different threads or multiple requests). These are just (few) general cases but it's hard to pick right one without more information (what's that file? where do you write it? where do you read it? is it shared by something else? - Adriano Repetti

1 Answers

0
votes

Taken from msdn.com which is saying that : "The specified file is in use. -or- There is an open handle on the file, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files. For more information, see How to: Enumerate Directories and Files."

take a look a this : http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx

Also doing some search on your own will prove to be efficient on the long run.

Best regards.