如何在ASP.NET MVC 4中检查文件是否存在

8

我正在开发一个基于ASP.NET MVC 4的应用。 我允许用户上传文件,但是我想在服务器上以不同的名称保存它们,因此我创建了一个helper方法来返回要使用的GUID。尽管它可能永远不会发生,但我仍然想检查是否有一个具有相同GUID名称的文件,因此我有以下代码:

public static string GetUniqueName(string pathToFile)
        {
            bool IsUnique = false;
            string guid = null;

            while (!IsUnique)
            {
                guid = Guid.NewGuid().ToString("N");
                var path = System.IO.Path.Combine(pathToFile, "login.jpg");

                if (!System.IO.File.Exists(path))
                {
                    IsUnique = true;
                }
            }

            return guid;
        }

正如您所见,文件名称是硬编码的,仅用于测试目的,因为我知道确实存在这样的文件。

为了保存文件,我使用以下代码:

var path = System.IO.Path.Combine(Server.MapPath("~/Content/NewsImages"), fileName);

而且它正常工作。所以当我尝试调用我的静态方法时,我像这样传递参数:

string test = Helper.GetUniqueName("~/Content/NewsImages");

但是在调试中,我看到了这个信息。
System.IO.Path.Combine(pathToFile, "login.jpg");

返回值为~/Content/NewsImages\\login.jpg,因此我决定更改传递的参数:

string test = Helper.GetUniqueName("~\\Content\\NewsImages");

现在的结果是~\\Content\\NewsImages\\login.jpg,这看起来很好,但接下来是:

            if (!System.IO.File.Exists(path))
            {
                IsUnique = true;
            }

尽管我知道在我想要检查的目录中存在这样的文件,但我还是通过了检查。 我该如何解决这个问题?

1个回答

21

当调用辅助方法时,您应该使用Server.MapPath,它将从虚拟路径转换为物理路径,例如:

string test = Helper.GetUniqueName(Server.MapPath("~/Content/NewsImages"));

谢谢,它修正了路径。现在根据预期返回正确的结果。 - Leron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接