FailedShack
FailedShack

Reputation: 91

How to get the original location of AppData\Roaming after the user has changed it?

I need to access contents in the folder %AppData%\Roaming\Microsoft.

This usually works fine by doing the following:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft");

The problem is that now the explorer lets you change the location of %AppData% by right clicking the Roaming folder and setting the location to some other place. However, this doesn't change the location of the Microsoft folder, which will remain in the original %AppData%.

I've thought about doing something like this:

string roaming = "C:\Users\" + Environment.UserName + @"\AppData\Roaming";

Though this just looks bad and looks like it could break easily. Any suggestions?

Upvotes: 1

Views: 2271

Answers (2)

Lemm
Lemm

Reputation: 196

You can try use following code to access %AppData%\Roaming\Microsoft:

string appData= Environment.ExpandEnvironmentVariables("%AppData%");
string roamingMicrosoft = Path.Combine(appData, @"Microsoft");

But I'm not really sure if Windows changes environment variable %AppData% by default when user changes path to AppData by it own.

Upvotes: 0

Anders
Anders

Reputation: 101606

I don't know if .NET can do it but WinAPI can. PInvoke SHGetFolderPath with the SHGFP_TYPE_DEFAULT flag:

using System;
using System.Runtime.InteropServices;

namespace Test { class TestApp {
public class WinApi
{
  public const int CSIDL_APPDATA = 0x1a;
  public const int SHGFP_TYPE_DEFAULT = 1;
  [DllImport("shell32.dll")]
  public static extern int SHGetFolderPath(IntPtr hwnd, int csidl, IntPtr hToken, uint flags, [Out] System.Text.StringBuilder Path);
}

[STAThread]
static void Main() 
{
  System.Text.StringBuilder builder = new System.Text.StringBuilder(260);
  int result = WinApi.SHGetFolderPath(IntPtr.Zero, WinApi.CSIDL_APPDATA, IntPtr.Zero, WinApi.SHGFP_TYPE_DEFAULT, builder);
  string path = "";
  if (result == 0) path = builder.ToString();
  Console.WriteLine(string.Format("{0}:{1}", result, path));
}
} }

Upvotes: 1

Related Questions