[英]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: 我有一个代码可以从放置在文本框中的路径加载xlsx,我的代码如下所示:
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? 有什么方法可以从项目目录将xlsx加载到datagridview? 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. 调试时,可执行文件位于bin\\Debug
文件夹中。 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. 您可能想要将xlsx文件放置在与可执行文件相同的目录中,因为在移动可执行文件时更容易维护。
My preferred solution would be to keep the xlsx file in AppData in a directory for your application. 我的首选解决方案是将xlsx文件保留在AppData中的应用程序目录中。 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;";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.