Is there a way to use "use" but leave the file open?

Generally, โ€œuseโ€ is the preferred approach for properly accessing and removing the filter.

I often need to leave the file open (as shown below). Can a โ€œusingโ€ structure be used in this case?

public class logger { private StreamWriter sw; public logger(string fileName) { sw = new StreamWriter(fileName, true); } public void LogString(string txt) { sw.WriteLine(txt); sw.Flush(); } public void Close() { sw.Close(); } } 
+5
source share
1 answer

Yes, you make Logger one-time and put it in your dispose method.

 // I make it sealed so you can use the "easier" dispose pattern, if it is not sealed // you should create a `protected virtual void Dispose(bool disposing)` method. public sealed class logger : IDisposable { private StreamWriter sw; public logger(string fileName) { sw = new StreamWriter(fileName, true); } public void LogString(string txt) { sw.WriteLine(txt); sw.Flush(); } public void Close() { sw.Close(); } public void Dispose() { if(sw != null) sw.Dispose(); } } 
+4
source

Source: https://habr.com/ru/post/1206260/


All Articles