garbage collect fileinfo in csharp

In C#, the FileInfo class represents a file in your file system. When you create a FileInfo object, you should dispose of it properly to avoid memory leaks.

You can dispose of a FileInfo object in two ways:

  1. Call the Dispose method explicitly:

    main.cs
    FileInfo fileInfo = new FileInfo("path/to/file.txt");
    fileInfo.Dispose();
    
    74 chars
    3 lines
  2. Wrap the FileInfo object in a using statement to have it automatically disposed of when the block of code is done executing:

    main.cs
    using (FileInfo fileInfo = new FileInfo("path/to/file.txt"))
    {
        // Use the fileInfo object here...
    }
    
    104 chars
    5 lines

By disposing of the FileInfo object, you are releasing the resources associated with it, including any file handles, and allowing the .NET garbage collector to free the memory used by the object. This helps to ensure the performance and stability of your C# program.

gistlibby LogSnag