在Assembly.Loadfile之后拒绝访问该路径

时间:2014-04-24 08:16:41

标签: c# asp.net web

我创建Web表单应用程序以上传文件(.exe)以获取程序集版本和删除文件(.exe)但在Assembly.LoadFile之后我无法删除文件,因为显示的错误是对路径的访问被拒绝。请向我解释这个问题。

protected void uploadBT_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {

                /** Save file to tmp **/
                string filename = FileUpload1.PostedFile.FileName;
                if (Directory.Exists(Server.MapPath("~/FilesUploaded/tmp")))
                {
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FilesUploaded/tmp/" + filename));
                }
                else
                {
                    Directory.CreateDirectory(Server.MapPath("~/FilesUploaded/tmp"));
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FilesUploaded/tmp/" + filename));
                }

                /** get assembly version **/
                Assembly ulf = Assembly.LoadFile(Server.MapPath("~/FilesUploaded/tmp/" + filename));
                string version = ulf.GetName().Version.ToString();

                DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/FilesUploaded/tmp"));

                FileInfo[] fi = di.GetFiles();
                for (int i = 0; i < fi.Length; i++)
                {
                    fi[i].Delete();
                }

                //Directory.Delete(Server.MapPath("~/FilesUploaded/tmp"), true);
                //Thread.Sleep(5);
                //Directory.CreateDirectory(Server.MapPath("~/FilesUploaded/tmp"));

                /** Save each versions **/
                //Directory.CreateDirectory(Server.MapPath("~/FilesUploaded/" + version));
                //FileUpload1.PostedFile.SaveAs(Server.MapPath("~/FilesUploaded/" + version + "/" + filename));
                errTxt.Text = "Completed !";
            }
            catch (Exception ex)
            {
                errTxt.Text = ex.Message.ToString();
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

  1. 文件被锁定,因为您已将其加载到内存中。
  2. 将任意可执行文件加载到Web服务器的内存中是一个巨大的安全漏洞。不要这样做!说真的,你不知道那个档案里有什么。
  3. 请改用:

    var version = AssemblyName.GetAssemblyName(
       Server.MapPath("~/FilesUploaded/tmp/" + filename)).Version;
    

    请参阅here