C# getting the path of %AppData%

后端 未结 10 2102
无人共我
无人共我 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:40

    I don't think putting %AppData% in a string like that will work.

    try

    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString()
    
    0 讨论(0)
  • 2020-11-22 14:41

    To get the AppData directory, it's best to use the GetFolderPath method:

    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    

    (must add using System if not present).

    %AppData% is an environment variable, and they are not automatically expanded anywhere in .NET, although you can explicitly use the Environment.ExpandEnvironmentVariable method to do so. I would still strongly suggest that you use GetFolderPath however, because as Johannes Rössel points out in the comment, %AppData% may not be set in certain circumstances.

    Finally, to create the path as shown in your example:

    var fileName = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.ApplicationData), "DateLinks.xml");
    
    0 讨论(0)
  • 2020-11-22 14:41

    You can also use

    Environment.ExpandEnvironmentVariables("%AppData%\\DateLinks.xml");
    

    to expand the %AppData% variable.

    0 讨论(0)
  • 2020-11-22 14:43

    AppData ⇝ Local aka (C:\Users\<user>\AppData\Local):

    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
    

    AppData ⇝ Roaming aka (C:\Users\<user>\AppData\Roaming):

    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    

    Additionally, it could be handy to know:

    • Environment.SpecialFolder.ProgramFiles - for Program files X64 folder
    • Environment.SpecialFolder.ProgramFilesX86 - for Program files X86 folder

    For the full list check here.

    0 讨论(0)
提交回复
热议问题