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:WindowsMicrosoft.NETFramework64v4.0.30319Temporary 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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?

Method 2

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

Method 3

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>

Method 4

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.

Method 5

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x