c00000fd
c00000fd

Reputation: 22327

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. (It is required while adding my site to IIS.) The folder on my local system is:

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?

Upvotes: 26

Views: 98449

Answers (5)

SaraFlower
SaraFlower

Reputation: 785

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:

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

Upvotes: 6

VahidN
VahidN

Reputation: 19206

Try System.Web.HttpRuntime.CodegenDir to get the physical path of directory where the ASP.NET temporary files are stored for the current application.

Upvotes: 12

c00000fd
c00000fd

Reputation: 22327

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. It is based on this sample, and also relies on the assumption that default ASP.NET temporary folders are hard-coded.

Correct me, if you find a better way?

Upvotes: 10

Naveed Butt
Naveed Butt

Reputation: 2901

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. Here are the attributes of the section...

Documentation here

Upvotes: 2

Piotr Stapp
Piotr Stapp

Reputation: 19838

Much more safe will be if you use your own temporary folder in for example App_Data

Unfortunately Path.GetTempPath(); won't return this folder because it is asp.net internal folder.

The good news is that you can change it specifing the file location in web.config with element.

Upvotes: 4

Related Questions