检查文件是否存在于ASP.NET MVC 5中 [英] Checking if file exists in asp.net mvc 5

查看:224
本文介绍了检查文件是否存在于ASP.NET MVC 5中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查文件bu的存在,无论它是否存在

I am checking for the existence of a file bu cannot find it, regardless of whether it is there or not

if (System.IO.File.Exists("~/files/downloads/" + fileCode + ".pdf"))
            {
                return File("~/files/downloads/" + fileCode, "application/pdf", Server.UrlEncode(fileCode));
            }
            else
            {
                return View("ErrorNotExistsView");
            }

如何修改代码以正确检查文件的存在?

How can I amend the code to check for the existence of the file correctly?

推荐答案

System.IO.File将起作用.相对路径将不是相对于HTML根文件夹,而是相对于当前工作目录.当前工作目录将是类似于C:\Program Files (x86)\IIS Express的值.

System.IO.File will work if you provide an absolute path or a relative path. A relative path will not be relative to the HTML root folder, but the current working directory. The current working directory will be a value like C:\Program Files (x86)\IIS Express.

文件路径开头的~字符仅被解释为当前ASP.NET上下文的一部分,而File方法对此一无所知.

The ~ character at the beginning of the file path is only interpreted as part of the current ASP.NET context, which the File methods know nothing about.

为您提供帮助的方法是

The method to help you here is HttpServerUtility.MapPath

如果您使用的是控制器方法,则可以在对象HttpContext.Server上调用此方法,否则(例如,在视图中)可以使用HttpContext.Current.Server.

If you are in a controller method, you can invoke this method on the object HttpContext.Server, otherwise (e.g. in a View) you can use HttpContext.Current.Server.

 var relativePath = "~/files/downloads/" + fileCode + ".pdf";
 var absolutePath = HttpContext.Server.MapPath(relativePath);
 if(System.IO.File.Exists(absolutePath)) ....

这篇关于检查文件是否存在于ASP.NET MVC 5中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆