C# getting the path of %AppData%
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");
C# How to get the User AppData folder, NOT AppData\Roaming?
First of all, accessing that folder directly is probably not a good idea unless Microsoft has published an API to retrieve its location. This means that there are no guarantees that this folder will even exist.
If you for some reason really want to retrieve this folder, you could probably do something along the lines of
Directory.GetParent(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))
Then to verify, you could also retrieve e.g.
Directory.GetParent(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData))
If the two are the same, it is likely the folder you want to find.
But again, it is probably a good idea to question the motivation on why you need this path in the first place.
Get AppData\Local folder for logged user
To get that information for another user, you'll need to know that user username/password, as is explained in this question.
So I'd like to throw an alternative solution:
1.- Instead of using the requestedExecutionLevel
for the aplication, remove it and run it as the logged user. That way you'll have access to the special folders path easily and may log it.
2.- Restart your application as Administrator.
Sample code (in App.xaml.cs):
private void Application_Startup(object sender, StartupEventArgs e)
{
if (!IsRunAsAdmin())
{
// here you should log the special folder path
MessageBox.Show(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
// Launch itself as administrator
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
// The user refused the elevation.
// Do nothing and return directly ...
return;
}
System.Windows.Application.Current.Shutdown(); // Quit itself
}
else
{
MessageBox.Show("The process is running as administrator", "UAC");
}
}
internal bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
This sample code is for a WPF Application, but could be done the same in a winforms Application.
Reference: UAC Self Elevation
How can i get the path of the current user's Application Data folder?
Look at combining Environment.GetFolderPath and Environment.SpecialFolder to do this.
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
How do I get %LocalAppData% in c#?
Environment.GetEnvironmentVariable("LocalAppData")
for C#, since Visual Studio isn't a language, unless you're looking to get that variable in one of the VS dialogs or something.
C# set appdata or any special folder path in app config file
Have you tried doing this via the app domain.
See:
https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.basedirectory?view=netframework-4.7.2
// Create application domain setup information
var domaininfo = new AppDomainSetup();
domaininfo.ConfigurationFile = System.Environment.CurrentDirectory +
Path.DirectorySeparatorChar +
"ADSetup.exe.config";
domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
//Create evidence for the new appdomain from evidence of the current application domain
Evidence adEvidence = AppDomain.CurrentDomain.Evidence;
// Create appdomain
AppDomain domain = AppDomain.CreateDomain("Domain2", adEvidence, domaininfo);
// Display application domain information.
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("Child domain: " + domain.FriendlyName);
Console.WriteLine();
Console.WriteLine("Configuration file: " + domain.SetupInformation.ConfigurationFile);
Console.WriteLine("Application Base Directory: " + domain.BaseDirectory);
AppDomain.Unload(domain);
Related Topics
Get Installed Applications in a System
Conditional Operator Cannot Cast Implicitly
List≪T≫ or Ilist≪T≫
When Should the Volatile Keyword Be Used in C#
Mssql Error 'The Underlying Provider Failed on Open'
When Is It Acceptable to Call Gc.Collect
What Are the Pros and Cons to Keeping SQL in Stored Procs Versus Code
Check If a Class Is Derived from a Generic Class
Deserializing Json to .Net Object Using Newtonsoft (Or Linq to Json Maybe)
How to Check If a Given String Is a Legal/Valid File Name Under Windows
How to Round a Number to Two Decimal Places in C#