I want to copy an excel file to my database. The problem I’m having is I cant seem to copy the path from into the code-behind. This is my asp code:
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
if I hard code in a path then my code will work:
string path = @"C:\Users\moynik\Desktop\datatest.xls";
but if I use the following line I only get a different path that will not work.
string path = Path.GetFullPath(FileUploadControl.FileName);
but I need to make my path dynamic so users can upload from different destinations on there own computer. Can anyone help me out. this is the function which works and copys the excel file to my database
If this is impossible can someone help me with a solution if they think of one. Thanks
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string path = @"C:\Users\moynik\Desktop\datatest.xls";
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
using (OleDbConnection connection = new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand ("Select Name,Address,Age FROM [Sheet1$]", connection);
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
string sqlConnectionString = "SERVER=<servername>;UID=schafc;Trusted_Connection=Yes;DATABASE=<dbname>;";
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "<tableName>";
bulkCopy.WriteToServer(dr);
}
}
}
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
Try
Path.GetFileName(FileUploadControl.FileName)instead of.GetFullPath.http://asp.net-tutorials.com/controls/file-upload-control/
EDIT: Ah, I’ve just worked out what you’re trying to do. You need to upload the xls file to a server location first, and then you can pass the path to the file on the server into the connection string.
e.g.