C# Can';I don’我的头绕不过去了

C# Can';I don’我的头绕不过去了,c#,asp.net,C#,Asp.net,这可能是显而易见的,但我对c#还不熟悉,所以要温柔点 我有一个应用程序(理论上)将文本文件解析为数组。尽管文本文件是aspx文件的对等文件,但我无法获得正确的相对路径。我不知道这是否有什么不同(我想不会),但我正在使用代码隐藏 我的文件夹结构如下所示: default.aspx default.aspx.cs default.aspx.designer.cs 相册 albums.txt web.config 这是我正在使用的代码: protected void Page_Load(obje

这可能是显而易见的,但我对c#还不熟悉,所以要温柔点

我有一个应用程序(理论上)将文本文件解析为数组。尽管文本文件是aspx文件的对等文件,但我无法获得正确的相对路径。我不知道这是否有什么不同(我想不会),但我正在使用代码隐藏

我的文件夹结构如下所示:

  • default.aspx
  • default.aspx.cs
  • default.aspx.designer.cs
  • 相册
  • albums.txt
  • web.config
这是我正在使用的代码:

 protected void Page_Load(object sender, EventArgs e)
    {

         string[] allLines = File.ReadAllLines(@"Albums.txt");
         Album[] Albums = new Album[allLines.Length];
         for (int i = 0; i < allLines.Length; i++)
         {
           string[] lineSplit = allLines[i].Split(',');
           Albums[i] = new Album();
           Albums[i].ID = Convert.ToInt32(lineSplit[0]);
           Albums[i].title = lineSplit[1];
           Albums[i].keyName = lineSplit[2];
       }
   }
受保护的无效页面加载(对象发送方,事件参数e)
{
字符串[]allLines=File.ReadAllLines(@“Albums.txt”);
相册[]相册=新相册[allLines.Length];
for(int i=0;i
然而,当我构建它时,我得到一个错误,说albums.txt找不到,它失败了

任何指点都将不胜感激


Ben

使用
Server.MapPath(filename)
获取文件的完整路径,而不仅仅是文件名


如果文件位于其他目录中,则可以使用
Server.MapPath(“~/path/to/the/file.txt”)
,其中~对应于web应用程序的根文件夹。

Server.MapPath指定要映射到物理目录的相对路径或虚拟路径

* Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
* Server.MapPath("..") returns the parent directory
* Server.MapPath("~") returns the physical path to the root of the application
* Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
例如:

假设您将一个web站点应用程序()指向

C:\Inetpub\wwwroot

并在中安装了您的商店应用程序(在IIS中将子网站作为虚拟目录,标记为应用程序)

D:\WebApps\shop

例如,如果在以下请求中调用Server.MapPath:

那么

如果路径以正斜杠(/)或反斜杠()开头,则MapPath方法将返回一个路径,就像路径是完整的虚拟路径一样

如果Path不是以斜杠开头,那么MapPath方法将返回相对于正在处理的请求的目录的路径

注意:在C#中,@是逐字逐句的字符串运算符,这意味着字符串应按“原样”使用,而不是针对转义序列进行处理


ReadAllLines采用绝对路径-您提供的是相对路径Server.MapPath用于将相对路径转换为绝对路径Server.MapPath(“~/Albums.txt”)将给出正确的值,而不管代码驻留在何处。此外,通过将文件置于~\App\u Data\下,您可以防止直接下载文件本身,并在应用程序运行时防止应用程序重复更新该文件(对App\u Data的更新不会生成文件更改通知

您是否尝试过使用Server.MapPath(“Albums.txt”)此网站?还是网络项目?i、 e.是否有csproj用于此?我想知道您是否只是没有告诉它txt文件将包含在构建输出中。(复制到输出目录)你是一个传奇!工作很愉快。堆栈溢出也是新手-我需要做点什么来分配点数/确认此修复是否正确吗?Server.MapPath对其进行了排序-感谢Omu(也为Marc的及时响应干杯。)@Ben,你在评论谁,Omu还是Marc?因此,评论和答案会根据您查看帖子的时间和方式而改变。因此,为了清晰起见,请使用“@username”来回答其他评论/答案。至于分数,正确的结果必须出现在答案中,而不是评论中,才能获得答案分数(通过单击鼠标悬停在评论上方时出现的向上箭头,您可以向上投票评论)。找到有效的答案(Server.MapPath?),单击左侧分数下的复选标记。根据你的判断,这“接受”了最好的答案,&奖励指向其作者。抄袭自??
* Server.MapPath(".") returns D:\WebApps\shop\products
* Server.MapPath("..") returns D:\WebApps\shop
* Server.MapPath("~") returns D:\WebApps\shop
* Server.MapPath("/") returns C:\Inetpub\wwwroot
* Server.MapPath("/shop") returns D:\WebApps\shop