从Excel Impot中的if else语句中断时创建的不需要的文件

时间:2011-12-28 03:55:33

标签: c# asp.net sql-server

我正在使用C#VS2005和SQL Server 2005。

我的网络应用程序有Excel导入功能。

如果用户选择的文件是正确的,并且我已经使用if-else语句检查文件内容类型,并且return;文件类型不正确,则导入工作正常。

但是,每当页面突破该功能时,我的目录C:\Documents and Settings\admin\My Documents\Visual Studio 2005\WebSites\MP\UploadFiles中都会创建一个不需要的文件。

在我的代码中,它应该突破该功能,并且在检查文件类型失败的情况下不应创建任何文件。

我试图对代码进行故障排除但无济于事。


创建的不需要文件的示例文件名是登录的用户名,后跟日期时间。

E.g。文件名: admin0120111228113732 ,我在下面的代码中看不到它是如何创建的。


我需要帮助来确定问题。

以下是我的代码段:

if (FileImport.HasFile)
        {
            string loginuser = (User.Identity.Name);
            SqlConnection thisConnection = new SqlConnection("DataSource");
            SqlCommand nonqueryCommand = thisConnection.CreateCommand();

            // 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" && strExtension != ".csv")
            {
                Response.Write("<script>alert('Error: Invalid Excel file');</script>");
                return;  //***UNREQUIRED FILE IS CREATED HERE***
            }
            if (strExtension == ".xls" || strExtension == ".xlsx")
            {
                    // Generate the file name to save. 
                    string strUploadFileName = "C:/Documents and Settings/admin/My Documents/Visual Studio 2005/WebSites/MP/UploadFiles/" + loginuser + 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 [Sheet1$]");

                        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 = "DataSource";

                            // Bulk Copy to SQL Server
                            using (SqlBulkCopy bulkCopy =
                                       new SqlBulkCopy(sqlConnectionString))
                            {
                                bulkCopy.DestinationTableName = "UserDB";
                                bulkCopy.WriteToServer(dr);

                            }
                        }
                    } File.Delete(@strUploadFileName);
                    return;
                }
            }

1 个答案:

答案 0 :(得分:-1)

我认为您应该保存文件而不管扩展名,将处理包装在try / finally语句中,并始终删除finally块中保存的文件。

<强>更新

显然至少有3个人不理解正确的编程习惯。

try / finally的目的是确保在任何情况下删除文件,因为OP明显关注搁浅的文件。

并且绝对没有额外保存文件;该文件已在Web服务器上。 SaveAs只是将文件从默认的IIS上传位置移动到已知位置,以便可以删除它,再次解决OP关于搁浅文件的问题。

不注意这些导致大多数编程问题的细节。

以下是如何重写的示例:

       try {
           // Generate the file name to save. 
           string strUploadFileName = "C:/Documents and Settings/admin/My Documents/Visual Studio 2005/WebSites/MP/UploadFiles/" + loginuser + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;

           // Save the Excel spreadsheet on server. 
           FileImport.SaveAs(strUploadFileName);

       // Validate the file extension. 
        if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv")
        {
            Response.Write("<script>alert('Error: Invalid Excel file');</script>");
            return;  //***UNREQUIRED FILE IS CREATED HERE***
        }
        if (strExtension == ".xls" || strExtension == ".xlsx")
        {
                // 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 [Sheet1$]");

                    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 = "DataSource";

                        // Bulk Copy to SQL Server
                        using (SqlBulkCopy bulkCopy =
                                   new SqlBulkCopy(sqlConnectionString))
                        {
                            bulkCopy.DestinationTableName = "UserDB";
                            bulkCopy.WriteToServer(dr);

                        }
                    }
                }
          } finally {
              File.Delete(@strUploadFileName);
          }