【问题标题】:How do I list the %TEMP% and %USERNAME% directory in C#?如何在 C# 中列出 %TEMP% 和 %USERNAME% 目录?
【发布时间】:2011-07-26 11:44:06
【问题描述】:

我正在尝试在文本框中列出目录 %TEMP% 和 %USERNAME% 中的文件,以便人们可以看到那里存在哪些文件。当我键入 C:\users\%username%... 时,它无法工作。 这是我的代码:

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";

感谢您抽出宝贵时间阅读本文。

【问题讨论】:

    标签: c# list variables path directory


    【解决方案1】:

    您需要做的是在程序中扩展%TEMP%%USERPROFILE% 环境变量,并使用结果而不是变量

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

    【讨论】:

      【解决方案2】:
      【解决方案3】:
      Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
      

      Environment.GetFolderPath 还允许访问许多其他特殊文件夹路径,例如 CD 刻录以及逻辑桌面和虚拟桌面位置。

      【讨论】:

        猜你喜欢
        • 2020-01-29
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-15
        • 1970-01-01
        相关资源
        最近更新 更多