无法访问System.IO.Directory.CreateDirectory生成的文件夹

时间:2014-12-16 01:21:07

标签: c# .net asp.net-mvc file-upload

我正在尝试上传文件。

当我发布文件时,我在下面调用fileUpload操作。

       [HttpPost]
       public void fileUpload(FormCollection fc)
       {
            string fileName = "";
            string directory = "";
            string uploadPath = "~/Files;

            if (Request.Files["Filename"] != null && Request.Files["Filename"].ContentLength > 0)
            {
                try
                {
                    fileName = Path.GetFileName(Request.Files["Filename"].FileName);
                    directory = Path.Combine(Server.MapPath(uploadPath), fileName);


                    Request.Files["Filename"].SaveAs(directory);

                }
                catch (Exception msg)
                {
                    ViewBag.Message = "Failed to upload your file.";
                }
            }
        }

上面的代码工作得很好。但是,如果我尝试创建一个目录,然后尝试将目标文件放入文件夹...

       [HttpPost]
       public void fileUpload(FormCollection fc)
       {

            string baseFolder = "Files";
            string yyyy = DateTime.Today.Year.ToString();
            string mm = DateTime.Today.Month.ToString();
            string fileName = "";
            string directory = "";
            string uploadPath = "~/" + baseFolder + "/" + yyyy + "/" + mm;

            if (Request.Files["Filename"] != null && Request.Files["Filename"].ContentLength > 0)
            {
                try
                {
                    fileName = Path.GetFileName(Request.Files["Filename"].FileName);
                    directory = Path.Combine(Server.MapPath(uploadPath), fileName);

                    if (!System.IO.Directory.Exists(directory))
                    {
                        System.IO.Directory.CreateDirectory(directory);
                    }

                    Request.Files["Filename"].SaveAs(directory);

                }
                catch (Exception msg)
                {
                    ViewBag.Message = "Failed to upload your file.";
                }
            }

这给了我一个跟随错误

E:\Monarch815MVC\Monarch815MVC\Files\2014\12\me.png' Access to the path is denied.

动态生成的文件夹非常可疑,不是吗?

我错过了什么吗?我是否需要为访问权限添加一些内容?

我用谷歌搜索了这个问题但没有找到。他们都在谈论“你应该给予文件夹完全许可”,

这不是我的答案。

1 个答案:

答案 0 :(得分:1)

您在使用文件名错误创建目录的代码中出错了

fileName = Path.GetFileName(Request.Files["Filename"].FileName);
directory = Path.Combine(Server.MapPath(uploadPath), fileName);

这将创建这样的目录并将文件名视为文件夹

E:\ Monarch815MVC \ Monarch815MVC \文件\ 2014 \ 12 \ me.png

更改此行,如下所示

directory = Server.MapPath(uploadPath);

您需要在创建目录

时组合上传文件的路径
Request.Files["Filename"].SaveAs(Path.Combine(directory, fileName));