Question

I am writing an application which requires the use of storing some temporary files (I am finding the temporary location through environment variables).

I understand that environment variables are variable which means they may or may not be there but is there any which are safer to rely on being there than others?

For example i could use APPDATA on windows 7 but I believe its not necessarily there on windows XP.

Était-ce utile?

La solution

Instead of using the environment directly I suggest that you use some of the support the .NET API can provide. There are two functions for temporary files:

  1. Path.GetTempPath() returns the path of the current user's temporary folder.

  2. Path.GetTempFileName() creates an empty file with a unique name in the user's temporary folder.

The temporary folder is actually found using the environment by using the Windows GetTempPath function. Typically the folder will be C:\Users\UserName\AppData\Local\Temp.

If you want an application specific folder for you own use you can employ a special folder:

const String CompanyName = "Acme Industries";
const String ApplicationName = "FooBar";
var subfolderName = Path.Combine(CompanyName, ApplicationName);
var folderName = Path.Combine(
  Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  subfolderName
);
Directory.CreateDirectory(folderName);

Typically the folder created will have the name C:\Users\UserName\AppData\Acme Industries\FooBar. Your application is free to use this folder and will not run into "read-only" issues.

Relying on a standard API allows your application to reliably run on different versions of Windows and in different environments (e.g. a terminal server).

Autres conseils

I strongly recommend not to use environment variables for your purpose.

If you do feel you have to use environment variables, I suggest you manually define these variables on the hosts you might need to use.

Different hosts may have the same environment variable pointing to other folders with different security settings and different purposes.

you can use %temp% or code below for path of your file:

string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".FileExtension";

or

string fileName = System.IO.Path.GetTempPath() + "FileName.FileExtension";

or try this link for create temp file: http://www.daveoncsharp.com/2009/09/how-to-use-temporary-files-in-csharp/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top