OleDbConnectionstring的问题 – 文件夹名称包含空格

我有OleDbConnectionstring格式的问题。 我使用OleDb类访问Excel文件。

这里是将excel表加载到数据集的方法。

public DataSet LoadExcelFileToDataSet(string file, string sheetName) { string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + ";" + "Extended Properties=Excel 8.0;"; var oledbConn = new OleDbConnection(connString); try { // Open connection oledbConn.Open(); // Create OleDbCommand object and select data from worksheet Sheet1 var cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "$]", oledbConn); // Create new OleDbDataAdapter var oleda = new OleDbDataAdapter { SelectCommand = cmd }; // Create a DataSet which will hold the data extracted from the worksheet. var ds = new DataSet(); // Fill the DataSet from the data extracted from the worksheet. oleda.Fill(ds, "SIMCards"); return ds; } catch(Exception ex) { throw ex; } finally { // Close connection oledbConn.Close(); } } 

这种方法效果很好。 问题是如果我尝试在WPF应用程序中使用相对path的这种方法。

 LoadExcelFileToDataSet(Config\\simcard.xls,sheetName) 

完整path是:E:\ C#PROJECTS \ AUSK \ T-TOOL \ T-TOOL \ bin \ Release \ Config \ simcard.xls

问题是这个文件夹名称C#PROJECTS – 包含空白

如果从这个文件夹名称中删除空格,它的效果很好。

但是如何解决呢? 更改文件夹名称不是我的解决scheme。

你可以尝试使用OleDbConnectionStringBuilder类:

 var sb = new System.Data.OleDb.OleDbConnectionStringBuilder(); sb.Provider = "Microsoft.Jet.OLEDB.4.0"; sb.DataSource = @"E:\C# PROJECTS\AUSK\T-TOOL\T-TOOL\bin\Release\Config\simcard.xls"; sb.Add("Extended Properties", "Excel 8.0"); MessageBox.Show(sb.ToString()); 

在文件周围放置[]:

 string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=[" + file + "];" + "Extended Properties=Excel 8.0;"; 

在我使用上述两个build议失败后,我将添加自己的经验。 上面的第一个解决scheme是将“Provider”设置为“DataSource”属性,而第二个解决scheme不适用于Microsoft.ACE.OLEDB.12.0提供程序,因为它们使用不包含括号的引号作为文件名称机箱。 所以,我的(testing)解决scheme是:

 Dim sb As OleDbConnectionStringBuilder = New System.Data.OleDb.OleDbConnectionStringBuilder() sb.Provider = "Microsoft.ACE.OLEDB.12.0" sb.DataSource = "c:\datafile.accdb" sb.OleDbServices = -1 Using connection As New OleDbConnection(sb.ToString()) .... End Using 

这结束了像一个string(注意引号):Provider = Microsoft.ACE.OLEDB.12.0; Data Source =“c:\ datafile.accdb”; OLE DB Services = -1