简体   繁体   中英

C# Load file from project folder

i have a question. I have a code to load xlsx from path i put in textbox and my code looks like this:

string PathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + safefilename.Text + ";Extended Properties=Excel 12.0;";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM [" + textBox_sheet.Text + "$]", conn); 

DataTable dt = new DataTable();

myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;

Is there any way to load xlsx to datagridview from project directory? So i don't have to put path everytime even if i switch to different computer.

When running the application, the directory the executable is located in will be the current directory ( .\\ ).

When debugging the executable is located in the bin\\Debug folder. Your project directory has the path ..\\..\\ :

string PathConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\" + safefilename.Text + ";Extended Properties=Excel 12.0;";

This will not work when you move the executable of your application, ..\\..\\ only refers to the directory two levels up in the directory hierarchy.

You'll probably want to either place the xlsx file in the same directory as the executable, as that's easier to maintain when moving the executable.

My preferred solution would be to keep the xlsx file in AppData in a directory for your application. You can move the file there when "installing" the application. You can then get a reference to the directory by doing this:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyApplication");

Leaving you with this:

string PathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyApplication", safefilename.Text) + ";Extended Properties=Excel 12.0;";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM