将文件上载到文件夹

时间:2015-04-08 13:32:57

标签: c# asp.net

使用下面的代码,我可以将文件保存到文件夹。

我的问题是只有两个上传字段是强制性的,其余三个不是。如果所有上传字段都选择了其他文件,则该代码将起作用,它会抛出NullReferenceException

if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
  int filesize = AnnualReport.PostedFile.ContentLength;
  int filesizeP = ProjectReports.PostedFile.ContentLength;
  int filesizePub = Publications.PostedFile.ContentLength;
  int filesizeOther = Other.PostedFile.ContentLength;
  int filesizeReg = RegistDoc.PostedFile.ContentLength;
  if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
    ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size  For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
  } else {
    const string ReportDirectory = "REPORTS/";
    //Other Document
    string OtherPath = ReportDirectory + Other.FileName;
    string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
    int iterationOther = 1; 
    while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
      OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
      iterationOther++;
    }
    //Registration Document
    string RigisDocPath = ReportDirectory + RegistDoc.FileName;
    string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
    int iterationRE = 1; 
    while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
      RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
      iterationRE++;
    }
    //Annual Reports
    string ReportPath = ReportDirectory + AnnualReport.FileName;
    string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
    int iteration = 1; 
    while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
      ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
      iteration++;
    }
    //Project Report
    string ProjecttPath = ReportDirectory + ProjectReports.FileName;
    string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
    int iterationP = 1; 
    while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
      ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
      iterationP++;
    }
    //publication 
    string publicationPath = ReportDirectory + Publications.FileName;
    string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
    int iterationPub = 1; 
    while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
      publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
      iterationPub++;
    }
    ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
    AnnualReport.SaveAs(Server.MapPath(ReportPath));
    Publications.SaveAs(Server.MapPath(publicationPath));
    RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
    Other.SaveAs(Server.MapPath(OtherPath));

2 个答案:

答案 0 :(得分:0)

您发布的代码格式很差。但是,您当前问题的解决方案是将空检查向下移动到每个单独的文档。

而不是做一个巨大的if行(逻辑有问题,因为它只检查是否上传了任何文件)

您只需检查必需文件是否存在。 (查看您的exising代码,present表示文档名称对象不为null) 如果没有,请抛出错误。

如果是,则继续执行其余代码,但将可选文档的单独处理包装在自己的null检查if-s中。

if (AnnualReport != null) {
//the block that does stuff with the anual report object
}

答案 1 :(得分:0)

我把代码放到了不同的方法中,比如@irreal建议,如下所示;

public void PublicationReporting() {

            //connection for the datareader
            string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
            SqlConnection csoW_connection = new SqlConnection(csoWConn);
            string database = csoW_connection.DataSource.ToString();
            csoW_connection.Open();

            if (Publications == null)
            {
                Publications.Dispose();

                ////
                String MyString = @"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
                SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
                int LastInsertedRecordID;

                LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());


            }
            else
            {
                int filesizeP = Publications.PostedFile.ContentLength;

                if (filesizeP > 2097152)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size  For Publication is 2.0 MB');", true);
                }

                else
                {

                    const string ReportDirectory = "REPORTS/";

                    //publication 
                    string publicationPath = ReportDirectory + Publications.FileName;
                    string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);

                    int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
                    {
                        publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
                        iteration++;
                    }


                    Publications.SaveAs(Server.MapPath(publicationPath));

                    String MyString = @"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
                    SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
                    int LastInsertedRecordID;

                    LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
                }

            }

        }

然后我将其称为点击事件

  try{
                              PublicationReporting();
                        }

                          catch (Exception ex)
                        {

                            pgError.Text = "Publication Exception Message: " + ex.Message;

                        }

                          finally
                          {
                              csoW_connection.Close();
                          }

从这里可以很容易地找出问题。

如果没有像这样选择文件

,我只需要在上传字段中处理内容
public void PublicationReporting() {

            //connection for the datareader
            string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
            SqlConnection csoW_connection = new SqlConnection(csoWConn);
            string database = csoW_connection.DataSource.ToString();
            csoW_connection.Open();

            if (Publications == null)
            {
                Publications.Dispose();

                ////
                String MyString = @"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
                SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
                int LastInsertedRecordID;

                LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());


            }
            else{

//程序继续}