简体   繁体   English

使用Server.MapPath定位正确的目录

[英]Using Server.MapPath to locate the correct directory

I'm building a webapp using ASP.NET. 我正在使用ASP.NET构建一个Webapp。

On my physical hard drive: 在我的物理硬盘上:

The path for my text file is: D:\\Users\\(MyName)\\Documents\\Visual Studio 2013\\Projects\\(ProjectName)\\(ProjectName)\\Data\\TextFiles\\someFile.txt 我的文本文件的路径是: D:\\Users\\(MyName)\\Documents\\Visual Studio 2013\\Projects\\(ProjectName)\\(ProjectName)\\Data\\TextFiles\\someFile.txt

The .cs file is located in: D:\\Users\\(MyName)\\Documents\\Visual Studio 2013\\Projects\\(ProjectName)\\(ProjectName)\\Account\\someCSFile.cs .cs文件位于: D:\\Users\\(MyName)\\Documents\\Visual Studio 2013\\Projects\\(ProjectName)\\(ProjectName)\\Account\\someCSFile.cs

In my code, I have the followings: 在我的代码中,我具有以下内容:

string fileName= Server.MapPath("TextFile/someFile.txt");

The code throws an exception saying that Could not find a part of the path 'D:\\Users\\(MyName)\\Documents\\Visual Studio 2013\\Projects\\(ProjectName)\\(ProjectName)\\Account\\TextFile\\someCSFile.cs 该代码引发异常,指出Could not find a part of the path 'D:\\Users\\(MyName)\\Documents\\Visual Studio 2013\\Projects\\(ProjectName)\\(ProjectName)\\Account\\TextFile\\someCSFile.cs

How am I going to use Server.MapPath to make it "go up one level", then find the "Data" folder > "TextFiles" > finally the "someFile.txt" WITHOUT hardcoding the entire file path? 我将如何使用Server.MapPath使其“向上一级”,然后找到“数据”文件夹>“文本文件”>最后是“ someFile.txt”,而无需对整个文件路径进行硬编码?

This should do the trick 这应该可以解决问题

string fileName= Server.MapPath(@"..\Data\TextFile\someFile.txt");

take a look at this: StackOverflow Post about Server.MapPath 看一下这个: 关于Server.MapPath的StackOverflow帖子

You can use .. to go up one level: 您可以使用..向上一级:

string fileName= Server.MapPath("../Data/TextFile/someFile.txt");

You can also start from the application root by starting the path with a slash: 您也可以通过使用斜杠开始路径从应用程序根目录开始:

string fileName= Server.MapPath("/Data/TextFile/someFile.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM