简体   繁体   English

Windows 窗体应用程序 vb.Net 中 xls 文件的相对路径

[英]Relative path for a xls file in Windows Form application vb.Net

enter image description here I am new to VB.Net and I am stuck in using the relative path for a xls file in vb.Net.在此处输入图像描述我是 VB.Net 的新手,我一直在使用 vb.Net 中的 xls 文件的相对路径。 I tried using resource file method but in vain.我尝试使用资源文件方法但徒劳无功。 Can somebody please help me.有人能帮帮我吗。

I have a VB.NET Windows Form application for which I am using an Excel file as my DB.我有一个 VB.NET Windows 窗体应用程序,我使用 Excel 文件作为我的数据库。 In my local system I can access that file by giving the full path.在我的本地系统中,我可以通过提供完整路径来访问该文件。 But if I have to run it on another system I need a relative path to the excel file.但是如果我必须在另一个系统上运行它,我需要一个到 excel 文件的相对路径。

How can I access an Excel file by giving its relative path in my VB.NET application?如何通过在我的 VB.NET 应用程序中提供其相对路径来访问 Excel 文件?

I would recommend using the following method, use Combine which will add the directory separator for you and AppDomain.CurrentDomain.BaseDirectory instead of Application.StartUpPath because it is not available when moving code to a class project.我建议使用以下方法,使用 Combine 将为您和 AppDomain.CurrentDomain.BaseDirectory 添加目录分隔符,而不是 Application.StartUpPath,因为它在将代码移动到类项目时不可用。 Of course the code sample below assumes the file is in the app folder, if in another location let us know.当然,下面的代码示例假定文件位于 app 文件夹中,如果位于其他位置,请告诉我们。

Dim fileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyFileName.xls")
If IO.File.Exists(fileName) Then
    ' do work
End If

Example例子

Dim Builder As New OleDbConnectionStringBuilder
Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
Builder.Add("Extended Properties", "Excel 8.0;IMEX=1;HDR=Yes;")
Builder.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Explanaation_notes.xls")
Dim con As New OleDbConnection(Builder.ConnectionString)

Here is a modified example to go with your last question for "Files" folder这是一个修改后的示例,用于解决“文件”文件夹的最后一个问题

Dim fileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files", "Explanaation_notes.xls")
If IO.File.Exists(fileName) Then
    Dim Builder As New OleDbConnectionStringBuilder
    Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
    Builder.Add("Extended Properties", "Excel 8.0;IMEX=1;HDR=Yes;")
    Builder.DataSource = fileName
    Dim con As New OleDbConnection(Builder.ConnectionString)
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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