llk
llk

Reputation: 2561

How do I list the %TEMP% and %USERNAME% directory in C#?

I am trying to list the files inside the directory %TEMP% and %USERNAME% in a text box so people can see what files exist there. When I type C:\users\%username%... It fails to work. Here is my code:

string strDirLocal = @"C:\users\USERPROFILE\desktop";
if (System.IO.Directory.Exists(strDirLocal))
{
   foreach (string sPath in System.IO.Directory.GetFiles(strDirLocal, "*.*"))
   {
       textBox1.Text = textBox1.Text + sPath.Replace(strDirLocal + @"\", "") + "\r\n";

Thank you for taking the time to read this.

Upvotes: 1

Views: 1031

Answers (3)

Pondidum
Pondidum

Reputation: 11637

Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

Environment.GetFolderPath also gives access to a lot of other special folder paths, such as CD Burning, and Logical Desktop & Virtual Desktop locations.

Upvotes: 2

JaredPar
JaredPar

Reputation: 755317

What you need to do is expand the %TEMP% and %USERPROFILE% environment variables in your program and use the result instead of the variable

string userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
string strDirLocal = Path.Combine(userProfile, "desktop");

Upvotes: 3

Related Questions