Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying with this below code for export access database table to csv file
but getting error
Quote:
"Object reference not set to an instance of an object." Null reference exception was unhandled.

Please provide solution for this.
this is my code
C#
private void button1_Click(object sender, EventArgs e)
       {
           OleDbConnection cnon = new OleDbConnection();
           cnon.ConnectionString = @"Provider= Microsoft.ACE.OLEDB.12.0; Data Source=D:\WindowsFormsApplication1\barcode.accdb";
           string query = "SELECT * FROM tblbarcode";
           string sep = ",";
           string strFilePath = @"D:\WindowsFormsApplication1\export.txt";


           StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(strFilePath));


           using (OleDbCommand Cmd = new OleDbCommand(query, cnon))
               {
                   cnon.Open();
                   using (OleDbDataReader dr = Cmd.ExecuteReader())
                   {
                       int fields = dr.FieldCount - 1;
                       while (dr.Read())
                       {
                           StringBuilder sb = new StringBuilder();
                           for (int i = 0; i <= fields; i++)
                           {
                               if (i != fields)
                               {
                                   sep = sep;
                               }
                               else
                               {
                                   sep = "";
                               }
                               sb.Append(dr[i].ToString() + sep);

                           }
                           sw.WriteLine(sb.ToString());
                       }
                   }
               }

       }
Posted
Updated 10-Nov-14 20:22pm
v2

1 solution

you don't need Server.MapPath, you already have physical path. do as below
C#
using(StreamWriter sw = new StreamWriter(strFilePath))
using (OleDbCommand Cmd = new OleDbCommand(query, cnon))
{
     // read from db and write file 

}
 
Share this answer
 
Comments
Member 10441729 11-Nov-14 3:40am    
Hi DamithSL thanks.... its working fine
DamithSL 11-Nov-14 3:41am    
you are welcome! please mark this as answer to your question

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900