Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose an object created by class FileInfo?

Tags:

c#

.net

I am using a

FileInfo

class to get the length of the file as follows:

FileInfo infoFile = new FileInfo(@"C:\Text12341234");
long configFileLength = infoFile.Length;

I want to dispose the object created by

FileInfo 

class. I am getting an error that "File has been already in use by another process." How can i do this?

like image 488
Manish Jain Avatar asked Oct 13 '14 09:10

Manish Jain


People also ask

What is FileInfo C#?

The FileInfo class is used to deal with file and its operations in C#. It provides properties and methods that are used to create, delete and read file. It uses StreamWriter class to write data to the file. It is a part of System.IO namespace.

What is the difference between using the File class and the FileInfo class?

Generally if you are performing a single operation on a file, use the File class. If you are performing multiple operations on the same file, use FileInfo . The reason to do it this way is because of the security checking done when accessing a file.


2 Answers

FileInfo does not implement IDisposable, hence you can't dispose it.

Any results from other methods you call on FileInfo which do implement IDisposable must be dealt with on the actual object, not on FileInfo.

You should use using:

using (FileStream s = File.Create(Application.StartupPath + @"\Client.config.xml"))
{
    // your code using s
}
like image 135
Patrick Hofman Avatar answered Sep 28 '22 18:09

Patrick Hofman


FileInfo doesn't open a stream.If you used methods like OpenRead you need to close the Stream you opened by calling Close method.Or simply wrap your statement with using.

like image 26
Selman Genç Avatar answered Sep 28 '22 18:09

Selman Genç