【问题标题】:Relative path to current directory in code-behind isn't consistent代码隐藏中当前目录的相对路径不一致
【发布时间】:2012-12-07 01:04:10
【问题描述】:

我有一个 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 发送不正确的文件(那里不存在。)

所以很明显,“./”指向我的第二个代码 sn-p 的不同文件夹,但我想指向第一个 sn-p 中使用的相同“./”。我需要做什么才能做到这一点?我想在这两个地方继续使用 ./ 作为 myfile.txt 的目录。

【问题讨论】:

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


    【解决方案1】:

    在 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\

    Appdomain C:\Users\Robert\documents\visual studio 2010\Projects\MvcTutorial\MvcTutorial

    环境 C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0

    【讨论】:

    • 太好了,我能够使用 new DirectoryInfo("./").FullName 让它工作
    【解决方案2】:

    您应该考虑使用Server.MapPath 创建在所有上下文中都应该正确的绝对系统路径(假设同一个应用程序)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 2011-04-25
      • 2016-12-25
      • 2021-06-24
      • 2011-02-03
      • 2014-04-14
      相关资源
      最近更新 更多