Using StreamReader when the File Doesn't exist

  • Thread starter Thread starter Rush
  • Start date Start date
R

Rush

If i create a new StreamReader object, based on a filename that does
not exist, the SR correctly raises an exception that the file doesn't
exist. Great! I love it.

BUT....then SR proceeds to create a zero length file using the
incorrect filename parameter!!

WTF??? Is this supposed to be a feature??? Creating a file as a
result of an exception? Isn't there a flag for this?

I'll guess I'll have to pass the filename through File.Exists() first,
then bypass StreamReader if false.

Anyone else experienced this?
 
Well that is the appropriate thing to do. You dont want exceptions at your
common program flow. However you can set the FileAccess and FileIO
permission on the reader so you dont get that.

Dave
 
Rush said:
If i create a new StreamReader object, based on a filename that does
not exist, the SR correctly raises an exception that the file doesn't
exist. Great! I love it.

BUT....then SR proceeds to create a zero length file using the
incorrect filename parameter!!

WTF??? Is this supposed to be a feature??? Creating a file as a
result of an exception? Isn't there a flag for this?

I'll guess I'll have to pass the filename through File.Exists() first,
then bypass StreamReader if false.

Anyone else experienced this?

Nope - and I can't reproduce it, either. Could you post some code which
demonstrates the problem? Here's my attempt to reproduce it, which
doesn't show the problem:

using System;
using System.IO;

public class Test
{
static void Main()
{
try
{
StreamReader sr = new StreamReader ("asd.txt");
}
catch (Exception e)
{
Console.WriteLine ("Exception {0}", e.Message);
}
}
}
 
I think its possible he might mean outside of a try catch block. Where if
you dont catch the exception it creates it.
 
I think its possible he might mean outside of a try catch block. Where if
you dont catch the exception it creates it.

That would require the StreamReader code to know whether or not it was
within a catch block - it's not going to know that.

Basically, I'll believe it when the OP provides an example program...
 
Back
Top