Uploading files in ASP.NET
I am trying to import an excel file using asp.net and C#. I found an example in VB, but it is using something called "Server.MapPath" which is not resolving to a namespace. I am on .NET 4.0, C#, and windows XP. I found a "HttpServerUtility.MapPath", but 开发者_开发百科I don't know if this is the equivalent for IIS7?
C#
public OleDbCommand ExcelConnection()
{
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/ExcelImport.xls") + ";" + "Extended Properties=Excel 8.0;";
//create your excel connection object using the connection string
OleDbConnection ocnct = new OleDbConnection(conStr);
ocnct.Open();
//use a SQL Select command to retrieve the data from the Excel Spreadsheet
//the "table name" is the name of the worksheet within the spreadsheet
//in this case, the worksheet name is "Members" and is coded as: [Members$]
OleDbCommand ocmd = new OleDbCommand("SELECT * FROM [Members$]", ocnct);
return ocmd;
}
Online Sample
Protected Function ExcelConnection() As OleDbCommand
' Connect to the Excel Spreadsheet
Dim xConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("~/ExcelImport.xls") & ";" & _
"Extended Properties=Excel 8.0;"
' create your excel connection object using the connection string
Dim objXConn As New OleDbConnection(xConnStr)
objXConn.Open()
' use a SQL Select command to retrieve the data from the Excel Spreadsheet
' the "table name" is the name of the worksheet within the spreadsheet
' in this case, the worksheet name is "Members" and is coded as: [Members$]
Dim objCommand As New OleDbCommand("SELECT * FROM [Members$]", objXConn)
Return objCommand
End Function
Server.MapPath
takes an application relative path (beginning with a ~
) and converts it to a full path on disk.
It is a member of the Server
object (an instance of the HttpServerUtility
class), which can be found on HttpContext
and on a page or user control.
If you already haev a full path on disk, you don't need it.
The HttpContext
and Page
classes both have a property named Server
which returns an HttpServerUtility
object (in fact, Page
just calls return this.Context.Server
).
Hence Server.MapPath
is HttpServerUtility.MapPath
.
It takes a string and computes the file path it would correspond to if that string were a relative URI backed with the out-of-the-box mapping between URIs handled by the application, and the file system (if you've complicated virtual directory mappings it handles that for you) with the added feature that if you begin with a tilde ~
then it considers that to be relative to the application root).
It can fail with values that are neither relative to the application root (begins with ~
) or the site root (begins with /
) if you've done some remapping along the way, but if you have done some remapping along the way, that's probably not your concern anyway.
精彩评论