Hi you all,
I have the following code to put a CSV file into a DataTable.

// read CSV file
        private DataTable BuildDataTable(string fileFullPath, char seperator)
        {
            const int EOF = -1;

            DataTable myTable = new DataTable("MyTable");
            DataRow myRow;
            try
            {
                StreamReader myReader = new StreamReader(fileFullPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error opening streamreader: " + ex.Message);
                return new DataTable("Empty");
            }
            try
            // Open file and read first line to determine how many fields there are.
            {               
                string[] fieldValues = myReader.ReadLine().Split(new Char [] {seperator,';'});
                // Adding the first line of data to data table (columnnames?
                // Create data columns accordingly
                for (int i = 0; i < fieldValues.Length; i++)
			    {
                    myTable.Columns.Add(new DataColumn(fieldValues[i].ToString().Trim()));
			    }          
                //Now reading the rest of the data to data table
                while (myReader.Peek() != EOF)
                {
                    fieldValues = myReader.ReadLine().Split(new Char [] {seperator});
                    myRow = myTable.NewRow();
                    for (int i = 0; i < fieldValues.Length; i++)
		            {   
                        myRow[i] = fieldValues[i].ToString().Trim();
		            }
                    myTable.Rows.Add(myRow);
                }
            }
            catch (Exception ex)
            { 
                MessageBox.Show("Error building datatable: " + ex.Message);
                return new DataTable("Empty");
            }
            finally
            {
                if (myReader != null)
                {
                    myReader.Close();
                }
            }
            myTable.AcceptChanges();
            return myTable;
        }

It actually works fine, except for line 10, I get an error if the same file is already open by another application.
So I though I would throw in another try catch block.
But then I get 5 errors that "The name 'myReader' does not exist in the current context"
What am I doing wrong here?
Any help, as always much appreciated :)

Why dont you put a StreamReader object out of any loops, so it can be accessible to any other sub brackets, loop, etc, like:

StreamReader myReder;
            DataTable myTable = new DataTable("MyTable");
            DataRow myRow;
            try
            {
               myReader = new StreamReader(fileFullPath);
            }

            //code continues..

Don't know really what you mean mitja.
If I just put

StreamReader myReader = new StreamReader(fileFullPath);

without the try catch block, the rest of my code works fine.
I just want to avoid the doom of someone else has opened the same file already.
StreamReader throws an exception in that case.
I want to intercept that exception.

Your StreamReader is only available in the block where it is declared (in the very small try {} catch. Move lines 11 through 16 to be inbetween lines 43 and 44 so the StreamReader will exist for the entire block of code.

This is what I meant:

// read CSV file
        private DataTable BuildDataTable(string fileFullPath, char seperator)
        {
            StreamReader myReader; //put a new instance of StreamReader here, so it will be accessable in whole method
            const int EOF = -1;

            DataTable myTable = new DataTable("MyTable");
            DataRow myRow;
            try
            {
                myReader = new StreamReader(fileFullPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error opening streamreader: " + ex.Message);
                return new DataTable("Empty");
            }
            try
            // Open file and read first line to determine how many fields there are.
            {
                string[] fieldValues = myReader.ReadLine().Split(new Char[] { seperator, ';' });
                // Adding the first line of data to data table (columnnames?
                // Create data columns accordingly
                for (int i = 0; i < fieldValues.Length; i++)
                {
                    myTable.Columns.Add(new DataColumn(fieldValues[i].ToString().Trim()));
                }
                //Now reading the rest of the data to data table
                while (myReader.Peek() != EOF)
                {
                    fieldValues = myReader.ReadLine().Split(new Char[] { seperator });
                    myRow = myTable.NewRow();
                    for (int i = 0; i < fieldValues.Length; i++)
                    {
                        myRow[i] = fieldValues[i].ToString().Trim();
                    }
                    myTable.Rows.Add(myRow);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error building datatable: " + ex.Message);
                return new DataTable("Empty");
            }
            finally
            {
                if (myReader != null)
                {
                    myReader.Close();
                }
            }
            myTable.AcceptChanges();
            return myTable;
        }

If this is not it, please let me know.
What bothers me, are those 2 chatch bloces. Do you have any issues with them? If not, its ok.

commented: For the effort! +8

Thanks guys for the effort you have put in.
@momerath: there has to be some line numbering mismatch in your answer(or a typo?), but don't worry.
@mitja: Finnaly I understood what you meant, it works, thank you!

He was saying the same thing as I was (no worries).

best regards,
Mitja

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.