C# getting the path of %AppData%

C# 2008 SP1

I am using the code below:

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

However, I am getting an exception that points to the location of where my application is running from:

Could not find a part of the path 'D:ProjectsSubVersionProjectsCatDialerbinDebug%AppData%DateLinks.xml'.

I thought the %AppData% should find the relative path. When I go Start|Run|%AppData% windows explorer takes me to that directory.

I can not put the full path in, as the user is different on each client machine.

Many thanks for any advice,


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

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

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

The path is different if you're talking ASP.NET.

I couldn't find any of the 'SpecialFolder' values that pointed to /App_Data for ASP.NET.

Instead you need to do this:

 HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data")  

(Note: You don't need the 'Current' property in an MVC Controller)

If theres another more 'abstract' way to get to App_Data would love to hear how.


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

    Remember some users type %AppData% , some %appdata% and some %APpData% You don't want to end up with:

    if (path.ToLower().StartsWith("%appdata%"))
        ; // path manipulation
    if (path.ToLower().StartsWith("%programfiles%"))
        ; // path manipulation
    

    If the environment variable is not set, it is not your fault (besides when it IS ). I usually don't tell people to not re-invent the wheel but after I first went the other way and realized that it was a bad idea.

    链接地址: http://www.djcxy.com/p/6126.html

    上一篇: C#将文件复制到具有权限的文件夹

    下一篇: C#获取%AppData%的路径