我的C#代码无法在IIS/ASP.NET中运行,我需要添加用户帐户权限到ASP.NET临时文件夹(将我的站点添加到IIS时需要)。 我本地系统上的该文件夹路径为:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files
我不想在我的代码中硬编码此路径,所以我想知道是否可以从.NET框架本身中检索它?
使用System.Web.HttpRuntime.CodegenDir
,获取当前应用程序存储ASP.NET临时文件的物理路径。
嗯,我不知道这会变得那么复杂。由于没有更好的答案,我能想到的就是这样:
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");
显然有两个临时文件夹--用于32位和64位进程。它基于这个示例,也依赖于假设默认的 ASP.NET 临时文件夹是硬编码
的。
如果您发现更好的方法,请纠正我?
最简单的验证方式:
if (file.ContentLength > 0)
{
string temp = Path.GetTempPath();
var path = Path.Combine(temp, fileName);
file.SaveAs(path);
}
在web.config文件中:
<system.web>
<compilation tempDirectory="D:\MyTempFiles" />
</system.web>
如果您在例如App_Data中使用自己的临时文件夹,则会更加安全。
不幸的是,Path.GetTempPath();
不会返回此文件夹,因为它是asp.net内部文件夹。
好消息是,您可以通过在web.config中指定文件位置的<tempDirectory>
元素来更改它。
%FrameworkInstallLocation%\Temporary ASP.NET Files
但我似乎无法扩展它。你有什么想法吗?这是源代码:http://msdn.microsoft.com/en-us/library/ms366723.aspx - c00000fdEnvironment.GetEnvironmentVariable("FrameworkInstallLocation")
,但是返回了 null
。 - c00000fdweb.config/machine.config
文件中的compilation tag
下有一个默认设置的路径部分。以下是该部分的属性...Path.GetTempPath()
时,会得到 C:\Users\Administrator\AppData\Local\Temp\
。 - c00000fd