Object reference not set to an instance of an object

Ruslan's ASP .NET weblog

CSV to TextReader

/// <summary>

/// Take a file path and return a TextReader

/// </summary>

/// <param name="file_path"></param>

/// <returns></returns>

private TextReader OpenFile (string file_path)

{

    try

    {

        // Read the CSV file in to a TextReader

        TextReader _rdr = File.OpenText(file_path);

        // Set file attributes

        File.SetAttributes(file_path, FileAttributes.Normal);

 

        return _rdr;

    }

    catch (Exception)

    {

        throw new Exception(String.Format(

                "Error trying to open file {0}. Check file exists and is accessible<br /><br />" +

                "Possible Issues:<br/><br />Files cannot be accessed via mapped network drives" +

                "<br />The file is open<br />The file has been viewed and then saved in Excel",file_path));

    }

}

Comments

Dmitriy Nagirnyak said:

This is not a good code:

1. Rethrowing exception without InnerException.

2. Formatting Exception Message as HTML is not probably a good idea.

3. General Exception handling. Catch specific ones for better description (such as FileNotFoundException) and do not catch the ones you don't expect.

4. Close TextReader. If error is raised after File.OpenText (eg: File.SetAttributes), the file will be locked forever (almost). Use "using" statement of "finally" block.

5. I assume it is used in ASP.NET and hopefully file_path is checked somewhere to make sure the file is allowed to be accessed by current user.

6. The method itself is called OPEN, but it MODIFIES file attributes. I would never guess OPEN method would be modifying the file. Even XML comments tell nothing about it. There's something terribly wrong.

In any case this code is not reusable. Might be fine for a quick, dirty implememntation if my suggestions will be applied.

But I don't actually understand creativity of this post. How is it different from MSDN Samples?

msdn2.microsoft.com/.../system.io.file.opentext(VS.71).aspx

I am probably missing some part: "CSV to TextReader".

How is the code above related to CSV and what have you tried to show?

Regards.

# February 19, 2008 7:43 AM

Dave Transom said:

Hi Ruslan,

I have to agree with Dmitriy on his points. The code doesn't really have anything to do with a csv either.

However, if you want a great CSV reader, try the lumen works one, on codeproject: www.codeproject.com/.../CsvReader.aspx

# February 19, 2008 4:48 PM

cannot open csv files said:

Pingback from  cannot open csv files

# May 15, 2008 7:06 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)