Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Manipulation in C#

Tags:

c#

file-io

How do I check if the following statement in my C# executed correctly?

StreamReader sr = new StreamReader(Path_To_File);
like image 505
zack Avatar asked Jun 30 '26 23:06

zack


1 Answers

If it didn't throw an exception, it executed correctly. If it throws an exception, it's reasonable to expect the cosntructor to tidy up after itself. Otherwise, it'll be up to you to call Dispose on it when you're finished, to release the associated resources. As others answers have said, you almost certainly want to use a using statement to accomplish this.

You might also want to use File.OpenText instead:

using (TextReader reader = File.OpenText(fileName))
{
}

I only usually use the StreamReader constructor when I need to pass in different options (which is pretty rarely).

like image 138
Jon Skeet Avatar answered Jul 04 '26 09:07

Jon Skeet