我有一个 asp.net 网站,它使用相对路径将一些数据写入TXT文件。它使用以下命令执行此操作:
string currentDirectory = "./";
string individualDeviceTxt = "myfile.txt";
System.IO.StreamWriter fileW3 = new System.IO.StreamWriter(currentDirectory + individualDeviceTxt);
文件成功写入以下路径:
C:\Program Files (x86)\Common Files\Microsoft shared\DevServer\10.0
但是,稍后,当我尝试将此文件传输给用户时,相对目录 ./指向不同的路径。这是代码:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Disposition", "attachment; filename=" + currentDirectory + individualDeviceTxt + ";");
response.TransmitFile(currentDirectory + individualDeviceTxt);
response.End();
它试图从'C:\Users\user\documents\visual studio 2010\Projects\myproject\myfile.txt发送文件,这是不正确的(它不存在)。
因此,很明显"./"指向我的第二个代码片段的不同文件夹,但我希望指向第一个代码片段中使用的相同"./"。我需要做什么才能实现这一点?我想继续使用 ./作为 myfile 的目录.txt在两个地方。
获取路径在 asp.net 中可能很棘手。
这里有四种不同的方法来获取当前路径,大多数只有两种提供相同的结果。 把它放在下面的服务器端代码中。 我喜欢使用AppDomain,它似乎是查找.aspx页面所在位置的最可靠方法。
string paths = " Runtime Path " + System.Reflection.Assembly.GetExecutingAssembly().Location + "<br>" +
" Using Root " + new DirectoryInfo("./").FullName + "<br>" +
" Appdomain " + Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) + "<br>" +
" Environment " + System.Environment.CurrentDirectory;
我得到的结果是。 希望这有帮助。
运行时路径 C:\Windows\Microsoft.NET\Framework\v4.0.30319\临时 ASP.NET 文件\root\e333f875\41caca57\assembly\dl3\9d915b4e\ee11a5b0_20d4cd01\mvc教程.DLL
使用根 C:\程序文件 (x86)\通用文件\Microsoft共享\开发服务器\10.0\
Appdomain C:\Users\Robert\documents\visual studio 2010\Projects\MvcTutorial\MvcTutorial
环境 C:\程序文件 (x86)\通用文件\Microsoft 共享\开发服务器\10.0
您应该考虑使用 Server.MapPath 创建在所有上下文中都应该正确的绝对系统路径(假设相同的应用程序)。