【发布时间】:2011-12-08 01:58:43
【问题描述】:
我是 ASP.NET 和 C# 的新手。我正在使用 VS2005 C# 和 SQL Server 2005。
我的 Web 应用程序中有两个导入函数,可将 Excel 电子表格中的数据导入 SQL Server 数据库。
导入功能工作正常。但是,由于对上传的 Excel 电子表格中的数据检查不当,可能会导致服务器停机。
下面是我的导入函数的代码 sn-p:
.XLS 和 .XLSX
if (FileImport.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(FileImport.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension == ".xls" || strExtension == ".xlsx")
{
// Generate the file name to save.
string strUploadFileName = "C:/Documents and Settings/user01/My Documents/Visual Studio 2005/WebSites/MajorProject/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
FileImport.SaveAs(strUploadFileName);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Excel 8.0;";
using (OleDbConnection connection =
new OleDbConnection(connStr))
{
string selectStmt = string.Format("Select [COLUMNS] FROM [userlist$]");
OleDbCommand command = new OleDbCommand(selectStmt, connection);
connection.Open();
Console.WriteLine("Connection Opened");
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<datasource>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "UserDB";
bulkCopy.WriteToServer(dr);
return;
}
}
}
.CSV*
if (strExtension == ".csv")
{
// Generate the file name to save.
string dir = @"C:\Documents and Settings\user01\My Documents\Visual Studio 2005\WebSites\MajorProject\UploadFiles\";
string mycsv = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
BaanImport.SaveAs(dir + mycsv);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties=Text;";
using (OleDbConnection ExcelConnection = new OleDbConnection(connStr))
{
string selectStmt = string.Format("SELECT [COLUMNS] FROM " + mycsv);
OleDbCommand ExcelCommand = new OleDbCommand(selectStmt, ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
using (DbDataReader dr = ExcelCommand.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<datasource>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "UserDB";
bulkCopy.WriteToServer(dr);
return;
}
}
}
}
情况 1 :例如我的SELECT 声明是Select [Username], [Description] FROM [userlist$]。如果我的 excel 电子表格看起来像这样,它将关闭整个服务器:
http://i.stack.imgur.com/Us9V3.png
请问有什么办法可以阻止用户上传这种包含超过 1 个列名的 excel 电子表格吗?
提前感谢您的帮助。
【问题讨论】:
标签: c# asp.net sql visual-studio