C# writing to a text file issue -
I have a simple enough class that is logging text into .txt file. I file does not exist Show me the code An exception will be received at the point I got. Then the text file appears in the text file after the file crashes. If I run the program, while the log.txt file exists, it works correctly.
code:
class logger {public string source; // public logger () // {//} public logger (string source) {checkexists (source); This.source = source + "log.txt"; } Private Zero CheckExists (string source) {if File! Exists (source + "log.txt")) {File.Create (source + "log.txt"); }} Public Zero WriteToLog {String Output} {Try {StreamWriter sw = file.AppendText (this.source)} {sw.WriteLine (Output); Sw.Close (); }} Hold (exception e) {// dot on which the code breaks; }}}}
The garbage collector runs, as long as the file opens < Code> FileStream which you want to close because it is open, you may be getting a sharing violation while trying to share it.
A better way to create a file is:
file. Write site (source + "log.txt", ""); which will close the file later.
Comments
Post a Comment