Close()方法在这里就是关闭连接的意思,当我们使用完数据库或数据流的时候,就要用Close()方法把它们关闭,然后使用Dispose()方法进行释放,避免占用资源。但要注意,使用Close()方法仅仅只是关闭连接,资源并没有被释放。我们可以直接使用Dispose()方法,因为Dispose方法里面会判断当前连接是否关闭,如果没有关闭,就会调用Close()方法先关闭掉连接,然后再进行资源的释放。在using语句执行完毕之后,程序会自动调用Dispose()进行释放,不需要我们显式的调用Dispose()方法。
using System; using System.IO; namespace ConsoleApp18 { class Program { static void Main(string[] args) { var filePath = Path.Combine(Environment.CurrentDirectory,"log.txt"); if(!File.Exists(filePath)) { File.Create(filePath); } using(StreamWriter sw = new StreamWriter(filePath,true)) { sw.WriteLine(DateTime.Now); sw.Flush(); } } } }