C# getting the path of %AppData%

后端 未结 10 2246
无人共我
无人共我 2020-11-22 13:50

C# 2008 SP1

I am using the code below:

dt.ReadXml(\"%AppData%\\\\DateLinks.xml\");

However, I am getting an exception that points t

10条回答
  •  一整个雨季
    2020-11-22 14:20

    The BEST way to use the AppData directory, IS to use Environment.ExpandEnvironmentVariable method.

    Reasons:

    • it replaces parts of your string with valid directories or whatever
    • it is case-insensitive
    • it is easy and uncomplicated
    • it is a standard
    • good for dealing with user input

    Examples:

    string path;
    path = @"%AppData%\stuff";
    path = @"%aPpdAtA%\HelloWorld";
    path = @"%progRAMfiLES%\Adobe;%appdata%\FileZilla"; // collection of paths
    
    path = Environment.ExpandEnvironmentVariables(path);
    Console.WriteLine(path);
    

    More info:

    %ALLUSERSPROFILE%   C:\ProgramData
    %APPDATA%   C:\Users\Username\AppData\Roaming
    %COMMONPROGRAMFILES%    C:\Program Files\Common Files
    %COMMONPROGRAMFILES(x86)%   C:\Program Files (x86)\Common Files
    %COMSPEC%   C:\Windows\System32\cmd.exe
    %HOMEDRIVE% C:
    %HOMEPATH%  C:\Users\Username
    %LOCALAPPDATA%  C:\Users\Username\AppData\Local
    %PROGRAMDATA%   C:\ProgramData
    %PROGRAMFILES%  C:\Program Files
    %PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
    %PUBLIC%    C:\Users\Public
    %SystemDrive%   C:
    %SystemRoot%    C:\Windows
    %TEMP% and %TMP%    C:\Users\Username\AppData\Local\Temp
    %USERPROFILE%   C:\Users\Username
    %WINDIR%    C:\Windows
    

提交回复
热议问题