Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to close a file after calling ReadAllText?

Tags:

c#

file

I am doing the following:

if (File.Exists(filePath))
{
   string base64 = File.ReadAllText(filePath);
   return new ImageContentDTO
   {
      ImageContentGuid = imageContentGuid,
      Base64Data = base64
   };
}

This works perfectly fine. What I want to ask is if I need to Close the file or anything similar after I am done reading from it. And if so, how?

like image 318
Subby Avatar asked Jul 16 '13 08:07

Subby


People also ask

Does file Readlines close File C#?

ReadAllLines(String, Encoding) Opens a file, reads all lines of the file with the specified encoding, and then closes the file.

How do you close a text file in C#?

Use it like this File. Create(myPath). Close(); .

What is ReadAllText C#?

ReadAllText(String, Encoding) is an inbuilt File class method that is used to open a text file then reads all the text in the file with the specified encoding and then closes the file.


1 Answers

I know this question has been answered and this is almost a year now but for those who search and read this question, I would like to suggest you close a file when done with it, or at least do an investigation like my answer shows.

I am no programming expert but I have come across this situation recently.

I created a WinForms c# program and used File.ReadAllText to copy text to a string. Afterwards I tried to delete the file, directly from the folder not through the program, but I got an error that the file was still open in another program. I then stopped running the program and was able to delete the file.

That's my experience in Visual Studio 2012 Ultimate. It might be supposed to do something different, but that's what it did for me.

When I used StreamReader.ReadToEnd then StreamReader.Close on the same file, I had no problem deleting the file while running the program.

like image 181
Alaba Baju Avatar answered Oct 18 '22 20:10

Alaba Baju