简体   繁体   English

获取ASP.NET临时文件夹路径

[英]Get ASP.NET temporary folder path

From my C# code, that doesn't run from within IIS/ASP.NET, I need to add a user account permissions to the ASP.NET temp folder. 从我的C#代码,不在IIS / ASP.NET中运行,我需要向ASP.NET临时文件夹添加用户帐户权限。 (It is required while adding my site to IIS.) The folder on my local system is: (将我的站点添加到IIS时需要。)本地系统上的文件夹是:

C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\Temporary ASP.NET Files C:\\ Windows \\ Microsoft.NET \\ Framework64 \\ v4.0.30319 \\ Temporary ASP.NET Files

I'd hate to hard-code this path into my code, so I was wondering if I can retrieve it from .NET framework itself? 我讨厌将这条路径硬编码到我的代码中,所以我想知道我是否可以从.NET框架本身检索它?

尝试使用System.Web.HttpRuntime.CodegenDir获取为当前应用程序存储ASP.NET临时文件的目录的物理路径。

Hmm. 嗯。 I didn't know that it would be so complicated. 我不知道会那么复杂。 For the lack of better answer, I was able to come up with something like this: 由于缺乏更好的答案,我能够想出这样的事情:

using System.Runtime.InteropServices;

string net_base = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), @"..\.."));
string strTemp32 = string.Concat(net_base, @"\Framework\", RuntimeEnvironment.GetSystemVersion(), @"\Temporary ASP.NET Files");
string strTemp64 = string.Concat(net_base, @"\Framework64\", RuntimeEnvironment.GetSystemVersion(), @"\Temporary ASP.NET Files");

There're obviously two temp folders -- for 32-bit and 64-bit processes. 显然有两个临时文件夹 - 用于32位和64位进程。 It is based on this sample , and also relies on the assumption that default ASP.NET temporary folders are hard-coded . 它基于此示例 ,并且还依赖于默认ASP.NET临时文件夹是hard-coded假设

Correct me, if you find a better way? 纠正我,如果你找到更好的方法?

Much more safe will be if you use your own temporary folder in for example App_Data 如果您在App_Data中使用自己的临时文件夹,则会更加安全

Unfortunately Path.GetTempPath(); 不幸的是Path.GetTempPath(); won't return this folder because it is asp.net internal folder. 不会返回此文件夹,因为它是asp.net内部文件夹。

The good news is that you can change it specifing the file location in web.config with element. 好消息是您可以使用element更改指定web.config中的文件位置。

Simplest way with validation: 最简单的验证方式:

if (file.ContentLength > 0)
{
    string temp = Path.GetTempPath();

    var path = Path.Combine(temp, fileName);
    file.SaveAs(path);
}

and in web.config: 并在web.config中:

<system.web>
  <compilation tempDirectory="D:\MyTempFiles" />
</system.web>

I think this should help... 我认为这应该有帮助......

There is a section in web.config/machine.config under the compilation tag where the path is set by default. compilation tag下的web.config/machine.config有一个部分,默认情况下设置路径。 Here are the attributes of the section... 以下是该部分的属性......

Documentation here 文档在这里

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

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