我有一个 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共享\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\Temporary ASP.NET Files\root\e333f875\41caca57\assembly\dl3\9d915b4e\ee11a5b0_20d4cd01\MvcTutorial.DLL
使用根目录 C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\
应用程序域 C:\Users\Robert\documents\visual studio 2010\Projects\MvcTutorial\MvcTutorial
环境 C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0
关于c# - 代码隐藏中当前目录的相对路径不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755399/