用户更改后如何获取AppData \ Roaming的原始位置?

时间:2019-06-03 16:35:02

标签: c# .net windows

我需要访问文件夹%AppData%\Roaming\Microsoft中的内容。

通常通过执行以下操作可以正常工作:

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

问题在于,现在资源管理器允许您通过右键单击漫游文件夹并将位置设置为其他位置来更改%AppData%的位置。但是,这不会更改Microsoft文件夹的位置,该位置将保留在原始%AppData%中。

我已经考虑过要做这样的事情:

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

尽管这看起来很糟糕,并且看起来很容易打破。 有什么建议吗?

2 个答案:

答案 0 :(得分:1)

我不知道.NET是否可以,但是WinAPI可以。 P用SHGetFolderPath标志调用SHGFP_TYPE_DEFAULT

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

答案 1 :(得分:0)

您可以尝试使用以下代码访问%AppData%\ Roaming \ Microsoft:

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

但是我不确定当用户自己更改AppData的路径时Windows是否默认更改环境变量%AppData%。