繁体   English   中英

如何使用C#在IIS Express中创建虚拟目录

[英]How to create a virtual directory in IIS Express using C#

您好,我的 controller 中有一个看起来像这样的方法。

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UploadImage(int? id)
        {
            if (id == null)
                return HttpNotFound();

            Component c = db.Components.Find((int)id);
            HttpPostedFileBase photo = Request.Files["image"];

            if (photo != null && photo.ContentLength > 0)
            {
                var filename = IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg";

                photo.SaveAs(filename);
                c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
                db.SaveChanges();
            }
            else
            {
                if (Request["imageurl"] != null && Request["imageurl"].Length > 0)
                {
                    // download this file
                    WebClient wc = new WebClient();
                    wc.DownloadFile(Request["imageurl"], IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg");
                    c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
                    db.SaveChanges();
                }

            }
            HttpPostedFileBase reference = Request.Files["referencefile"];

            if (reference != null && reference.ContentLength > 0)
            {
                // Upload the origin file and create a URL 
                var filename = IGT.contentPath + "\\uploads\\Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
                reference.SaveAs(filename);
                c.Reference_Url = IGT.baseUrl + "/Content/uploads/Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
                db.SaveChanges();

            }

            return RedirectToAction("Edit", new { id = id });
        }

但目前当它到达

photo.SaveAs(filename);

我收到错误信息

System.IO.DirectoryNotFoundException: '找不到路径的一部分 'C:\Users\chris\Source\Repos\inventory2.0\PIC_Program_1.0\Content\images\Components\498.jpg

我怎样才能制作一个 try catch 块,以便如果 IIS Express 中不存在该文件夹,它将创建它?

您可以使用以下代码以编程方式创建目录:

 if (!Directory.Exists(appDataPath)) {
     Directory.CreateDirectory(appDataPath);
 }

并使用directory.SetAccessControl(security); 方法来设置该文件夹的权限。

请参考以下链接了解更多详情:

https://learn.microsoft.com/en-us/do.net/api/system.io.directory.createdirectory?view.netframework-4.8

C# 创建目录并设置权限

https://www.kunal-chowdhury.com/2016/02/folder-permission.html

你能试试这段代码吗:

if (!System.IO.Directory.Exists("your folder")) {
                System.IO.Directory.CreateDirectory("Your Folder");
            }

此外,请确保您的 IIS 用户对该文件夹目录具有读/写访问权限。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM