c# - 代码隐藏中当前目录的相对路径不一致

标签 c# asp.net visual-studio-2010 httpresponse relative-path

我有一个 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/

相关文章:

c# - .net 序列化 : How to use raw binary writer while maintaining which thing is which

c# - LINQ:分组依据,并检索公共(public)属性

c# - 我的 Access 数据库不更新 (ASP.NET)

sql-server - 已安装 VS2012 - 现在无法使用 SSMS 连接到 SQL 服务器

c# - 如何使用中间 API 传递 JSON 对象?

c# - 如果类型相同,Array.ToArray<>() 是否返回原始数组?

asp.net - 在同一端口上运行 Angular 和 ASP.NET Web API

c# - 在 asp.net 的图表控件中绘制条形图和折线图

c++ - "Missing type specifier int assumed"C++ 问题

c++ - 在 incredibuild 中启用 Microsoft Visual Studio x64 工具