Skip to main content
 首页 » 编程设计

C#路径问题

2024年02月23日16mfryf

我有这个文件:C:\Documents and Settings\extryasam\My Documents\Visual Studio 2010\Projects\FCR\WebApplication4\config\roles.txt 我想将它导入我的 C# 应用程序。如果我插入完整路径就没问题,但我想做一些类似于我们对网站所做的事情,那就是“\config\roles.txt”

但是对于下面的代码,这是行不通的。

这是我的代码:

    public string authenticate() 
    { 
        WindowsIdentity curIdentity = WindowsIdentity.GetCurrent(); 
        WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity); 
 
        //String role = "NT\\Internet Users"; 
 
        //string filePath = Server.MapPath("config/roles.txt"); 
        //string filePath = (@"~/WebApplication4/config/roles.txt"); 
        //string filePath = Path.GetDirectoryName(@"\config\roles.txt"); 
        string filePath = Path.GetPathRoot(@"/config/roles.txt"); 
        string line; 
        string role = ""; 
 
        if (File.Exists(filePath)) 
        { 
            StreamReader file = null; 
            try 
            { 
                file = new StreamReader(filePath); 
                while ((line = file.ReadLine()) != null) 
                { 
                    role = line; 
                } 
            } 
            finally 
            { 
                if (file != null) 
                { 
                    file.Close(); 
                } 
            } 
        }  
 
        if (!myPrincipal.IsInRole(@role)) 
        { 
            return "401.aspx"; 
        } 
        else 
        { 
            return "#"; 
        } 
    } 

请您参考如下方法:

在 ASP.NET 中,您可以使用 ~/config/roles.txt - 结合 Server.MapPath(),您可以获得完整路径。

[...] ASP.NET includes the Web application root operator (~), which you can use when specifying a path in server controls. ASP.NET resolves the ~ operator to the root of the current application. You can use the ~ operator in conjunction with folders to specify a path that is based on the current root. (see http://msdn.microsoft.com/en-us/library/ms178116.aspx)

所以你可以尝试以下方法:

string filePath = System.Web.HttpContext.Current.Server.MapPath("~/config/roles.txt");