gpt4 book ai didi

C#路径问题

转载 作者:太空宇宙 更新时间:2023-11-03 22:10:10 25 4
gpt4 key购买 nike

我有这个文件: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");

关于C#路径问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6923521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com