What determines the return value of Path.GetTempPath()?

后端 未结 6 391
忘了有多久
忘了有多久 2020-12-08 13:20

Currently, I use Path.GetTempPath() to figure out where to write my log files, but recently I came across a user\'s machine where the path returned was not what

6条回答
  •  眼角桃花
    2020-12-08 13:41

    I've noticed GetTempPath() can bring back the local user's Documents & Settings\user\Local Settings\Temp path if it's a console application, and noticed it can bring back C:\WINDOWS\Temp (on the server) if it's a web app being ran from a client. In the former case, no big deal - the account running the app has the rights to that folder. In the latter, maybe it is a big deal if the App Pool Identity account (or account you may be using to impersonate with in the Web.config file for the web app) doesn't have privileges to C:\WINDOWS\Temp on the server (which is a big chance it doesn't). So for my console apps, just so there's no question where temp files are written, hard-coding a string into an INI file is the best and easiest for me, and for a web app, hard-coding it in the web.config and getting it using ConfigurationManager.AppSettings["myKey"] works, or if it's a web app, use this function to send the file to the ASP Temporary Files folders and work with it there:

    public static string findFileDirectory(string file)
    {
        // Get the directory where our service is being run from
        string temppath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        // Ensure proper path notation so we can add the INI file name
        if (!temppath.EndsWith(@"\")) temppath += @"\";
    
        return temppath;
    }
    

    and call it like this:

        string tempFolderPath = findFileDirectory("Web.config");
        tempFolderPath = tempFolderPath.Replace(@"\\", @"\");
    

    and just use "tempFolderPath" instead of where you used Path.GetTempPath() before. This function works awesome & I use it in my code in place of this evil GetTempPath() method so I know my app can do what it needs to do, since the ASP Temp Files folder should have all the permissions it needs for its operations (DOMAIN\NETWORK SERVICE and App Pool ID account need Full Control). tempFolderPath ends in a trailing slash, so just concat directly with your variable/file name to get the right path going.

    -Tom

    P.S. You need to add 2 namespaces to make that function work: System.IO and System.Reflection

提交回复
热议问题