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));

    }

}

Published Tuesday, February 19, 2008 11:11 AM by funky_rus

Comments

# re: CSV to TextReader

Tuesday, February 19, 2008 7:43 AM by Dmitriy Nagirnyak

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.

# re: CSV to TextReader

Tuesday, February 19, 2008 4:48 PM by Dave Transom

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

# cannot open csv files

Thursday, May 15, 2008 7:06 AM by cannot open csv files

Pingback from  cannot open csv files

Leave a Comment

(required) 
(required) 
(optional)
(required)