CategoryFileInfo

Implementing IDisposable

As we saw in previous post, we can use using statement to automatically dispose of objects. To use using directive our class needs to implement IDisposable interface.  To correctly implement IDisposable interface we should stick to some guidelines. Following example will show you the correct way to implement it.

Example of Implementing IDisposable interface to a class

We will start by creating FileRead class whose job is to create file and write line to it. FileRead class will implement IDispose interface and two Dispose methods. General rule is that you should create two Dispose methods:

  • public void method with no parameters
  • protected void method with a boolean input parameter

Job of public Dispose method is to call second Dispose method where objects are really disposed of, and second job is to notify Garbage collector that this instance of class is cleaned up and that there is no need to check-up upon it during garbage collection.

More examples of IDisposable coming up soon.

Garbage Collector

Have you ever wondered how applications know how much memory to use, how is that memory distributed or who cleans up memory? All those operations are executed by the Garbage Collector.

What triggers Garbage collector?

  • Your system is low on physical memory.  Meaning your system has used up almost all of your RAM memory and will start to use page file.
  • The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
  • Application is written to call the GC.Collect method.

Continue reading

File and FileInfo

While trying to copy, move, rename, create, open, delete and appending to files we use File and FileInfo classes. File and File info classes derive from System.IO namespace. File class provides us static methods to work with files and FileInfo provides us with instance methods. Generally, you will use File class when working with a file and perform one operation on it. Difference between File and FileInfo approaches is that FileInfo does security checking only once (while accessing files).  Because FileInfo is a instance method it does not tack changes to a file so you will have to take a lot of precautions while using that class. File class is on a disadvantage, because you always have to apply path to a file, meaning, it takes more parameters than FileInfo class. Try discovering yourself which approach is faster in your scenario. Also both classes help us while creating FileStream (to be explained in next post).

Common operations working with File class

 

Common operations working with FileInfo  class

 

I hope you had no problem with learning how to use File and FileInfo classes. If you found File and FileInfo classes interesting I recommend that you continue learning about Streams.

© 2019 LearnC#WithDarko

Theme by Anders NorenUp ↑