I'm writing an app which needs a permission for accessing a text file cuz without permission it throws an exception "access denied".
I added to the Package.appxmanifest specific lines
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities
"IgnorableNamespaces="uap mp rescap"
And
<rescap:Capability Name="broadFileSystemAccess" />
But still it doesn't work. Is there any other way to access specific file with picker?
Yes the behavior changed between the April 2018 and October 2018 releases, and the default is now Disabled. This is a privacy constraint - we're very focused on maintaining the user's privacy. The documentation for this is up-to-date: https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions#accessing-additional-locations. As of right now, if you want to detect whether the setting is enabled or disabled, you can simply try to access some file/folder to which this setting would grant you permission if enabled and deny permission if disabled (eg, "C:\"). If disabled, you can then launch the Settings app on the File System privacy page. For example:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(#"C:\");
// do work
}
catch
{
MessageDialog dlg = new MessageDialog(
"It seems you have not granted permission for this app to access the file system broadly. " +
"Without this permission, the app will only be able to access a very limited set of filesystem locations. " +
"You can grant this permission in the Settings app, if you wish. You can do this now or later. " +
"If you change the setting while this app is running, it will terminate the app so that the " +
"setting can be applied. Do you want to do this now?",
"File system permissions");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(InitMessageDialogHandler), 0));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler(InitMessageDialogHandler), 1));
dlg.DefaultCommandIndex = 0;
dlg.CancelCommandIndex = 1;
await dlg.ShowAsync();
}
}
private async void InitMessageDialogHandler(IUICommand command)
{
if ((int)command.Id == 0)
{
await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-broadfilesystemaccess"));
}
}
You can use the methods on the AppCapability class to query the state of the capability for the app and request access, which, may prompt the user depending on a number of geopolitical constraints that are subject to change over time. The CheckAccess() method will provide the status of the capability at the time of the call. The app can adjust it's behavior based on the results. Ideally the app would display some sort of indication to the user if it is operating in a reduced functionality mode, with a link to more details and instructions on how to enable the full functionality.
Related
I am simply trying to recover if a process is running but impossible, an error is repeated for whatever reason...
I don’t understand, after research I thought I understood that it was not possible but I can’t believe it, there is necessarily a way to recover if a program is running.
I already used Process.GetProcessesByName on WinForm and no problem... But this time with UWP i have an error... I just try to check is TeamSpeak is running
public bool isTSOpen()
{
Process[] processesx64ts = Process.GetProcessesByName("ts3client_win64");
Process[] processesx32ts = Process.GetProcessesByName("ts3client_win32");
if(processesx32ts.Length == 0 && processesx64ts.Length == 0)
{
return true;
}
else
{
return false;
}
}
Retrieving information about local processes is not supported on this platform.
At System.Diagnostics.NtProcessInfoHelper.GetProcessInfos(Predicate'1 machineName)
at System.Diagnostics.Process.GetProcesses(String machineName)
at System.Diagnostics.Process.GetProcessesByName(String processName, String machineName)
You need to run with App Diagnostics capability
You can use appdiagnosticinfo. I think you need to request user permission the first time.
https://learn.microsoft.com/en-us/uwp/api/windows.system.appdiagnosticinfo
https://www.google.com/amp/s/blogs.windows.com/buildingapps/2017/06/28/uwp-app-diagnostics/amp/
#Andy's suggestions was on the right direction. The UWP has diagnostic APIs to allow an app to enumerate a list of running apps, including UWP apps, Win32 apps, system services and so on.
To make the APIs work successfully, you need to declare the appDiagnostics capability in your manifest.
<Package xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp rescap">
...
<Capabilities>
<rescap:Capability Name="appDiagnostics" />
</Capabilities>
</Package>
Please note:
This is a restricted capability: If you submit an app with this capability to the Windows Store, this will trigger closer scrutiny. The app must be in the Developer Tools category, and we will examine your app to make sure that it is indeed a developer tool before approving the submission.
At run time, the capability also triggers a user-consent prompt the first time any of the diagnostic APIs are called.
The user is always in control: If permission is denied, then the APIs will only return information about the current app. The prompt is only shown on first use, but the user can change his or her mind any time via the privacy pages in Settings.
More information, please see UWP App Diagnostics
Back to your original question, you want to find the specific process.
You first need to request permission to access diagnostics for other apps by calling AppDiagnosticInfo.RequestAccessAsync method and then, you could ProcessDiagnosticInfo.GetForProcesses method to get all running processes. At the end, you could get the specific process by its ExecutableFileName property.
I made a simple code demo for your reference:
DiagnosticAccessStatus diagnosticAccessStatus =
await AppDiagnosticInfo.RequestAccessAsync();
switch (diagnosticAccessStatus)
{
case DiagnosticAccessStatus.Allowed:
IReadOnlyList<ProcessDiagnosticInfo> processes = ProcessDiagnosticInfo.GetForProcesses();
var p = processes.Where(x => x.ExecutableFileName == "ts3client_win64.exe"||x.ExecutableFileName == "ts3client_win32.exe").FirstOrDefault();
if (p!= null)
{
//TODO:...
}
break;
case DiagnosticAccessStatus.Limited:
break;
}
I have an application that should be able to run explicit tasks in another users context, so that within the application, a less privileged user is able to do some tasks, he is not allowed to.
I used for this an impersonation and it works fine with the acutal code, but I can not make it work with a Folderbrowser Dialog. I think the browser is executed within the context of the correct user, but uses other windows functions which override the user context.
My code that does not work is:
private void tb_customRoot_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ImpersonationHelper.Impersonate("STARK", VSSFileExplorer.Properties.Settings.Default.FS_User, BASE64.Base64Decode(VSSFileExplorer.Properties.Settings.Default.FS_Password), delegate
{
VistaFolderBrowserDialog myFancyFolderDialog = new VistaFolderBrowserDialog();
DirectoryInfo rootDir = new DirectoryInfo(#"C:\");
try
{
rootDir = new DirectoryInfo(VSSFileExplorer.Properties.Settings.Default.CustomRoot);
}
catch
{ throw; }
myFancyFolderDialog.SelectedPath = rootDir.ToString();
myFancyFolderDialog.ShowDialog();
tb_customRoot.Text = myFancyFolderDialog.SelectedPath;
});
}
The problem is, that after opening the browser dialog, windows opens a "Enter network credentials" login prompt. The user should not know this credentials.
Is there a way to run a Folderbrowserdialog with another users rights?
I also build a function which will generate the correct path from some Tools in the GUI, but I am really interested if this is possible.
Thanks in advance.
i cannot create file in my windows service
and this is error
error In onstart method Access to the path 'C:\Windows\system32\BridgeServiceLog.txt' is denied.
protected override void OnStart(string[] args)
{
try
{
Logger.InitLogFile("BridgeServiceLog.txt");
Trace.WriteLine(Logger.logSwitch.TraceInfo, "Trace Started");
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Started");
_bridgeServiceEventLog.WriteEntry("new OnStart");
if (Vytru.Platform.Bridge.Configuration.LicenseValidetor.ValidCountAndTypeDevices())
{
SharedData.InitializeBridge();
// WsInitializeBridge();
}
else
{
this.Stop();
_bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
}
_bridgeServiceEventLog.WriteEntry("end Start");
}
catch (Exception e)
{
Trace.WriteLineIf(Logger.logSwitch.TraceError, e.Message);
_bridgeServiceEventLog.WriteEntry("error In onstart method " + e.Message);
}
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Ended");
}
The service user account probably doesn't have access to write to C:\Windows\System32 (which is the working directory of a Windows service).
Anyway, you shouldn't write to that folder. It is for the operating system - not your service.
You can use Environment.GetFolderPath to get a suitable path for writing files like log files in a way that will work any computer, not just your own computer. Here is an example.
var companyPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyCompany"
);
var productPath = Path.Combine(companyPath, "MyProduct");
var logFilePath = Path.Combine(productPath, "BridgeServiceLog.txt");
You should of course use suitable values for MyCompany and MyProduct.
When running a Windows Service the default working folder is <System drive>:\Windows\System32\.
Fortunately, not everyone can just access that folder.
There are two ways about this; write your file to another folder to which you do have rights, or run your service with administrator rights.
I would recommend the first option.
The easiest solution is to go the folder where you want to save a file, right click, properties, security, add a new user IIS_Users and give permission to write.
Use LocalSystem account on ProjectInstaller
I have an ASP.NET application which requires write access on the App_Data subfolder. The MSI used to deploy the application tries to set the permissions correctly, but in spite of this, it seems the permissions are sometimes wrong. Most of the application works fine without this permission. I would prefer that the application fails to start if the permissions are wrong.
What is the best practice for ensuring that the necessary permissions are correct for the IIS user context? Ideally I want to display some simple instructions for fixing whatever is wrong. And I want the message to appear in as many incorrect configurations as possible.
The following describes what I've tried so far, until I realised there's a probably a better or standard way.
I tried putting this in Application_Start()
protected void Application_Start(Object sender, EventArgs e)
{
// Assert permissions on writeable folders are correct
var permissionsChecker = new AppDataPermissionsChecker();
permissionsChecker.AssertFolderIsWriteable(
HttpContext.Current.Server.MapPath("~/App_Data"));
// remainder of Application_Start()...
}
where AppDataPermissionsChecker is defined as follows:
public class AppDataPermissionsChecker
{
private bool CanWriteAccessToFolder(string folderPath)
{
try
{
// Attempt to get a list of security permissions from the folder.
// This will raise an exception if the path is read only or do not have access to view the permissions.
DirectorySecurity directorySecurity = Directory.GetAccessControl(folderPath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
public void AssertFolderIsWriteable(string folderPath)
{
if (!Directory.Exists(folderPath))
throw new Exception(String.Format("The {0} folder does not exist.", folderPath));
if (!CanWriteAccessToFolder(folderPath))
throw new Exception(String.Format("The ASPNET user does not have "
+ "access to the {0} folder. Please ensure the ASPNET user has "
+ "read/write/delete access on the folder. See 'The App_Data folder' "
+ "here: http://msdn.microsoft.com/en-us/library/06t2w7da.aspx'",
folderPath));
}
}
I thought this would throw an ugly exception if the rights are incorrect (which is better than nothing), but in some situations I just get an HTTP Error 503.
I found this implementation of a diagnostics page which does exactly what I was looking for (and more besides).
I made an app that allows windows users to spoof Mac Address .
It works by adding "NetworkAdapter": "00ff00ff00ff" key/value pair to registry of the users selected nic.
The problem is that every time the app tries to make changes to windows registry Windows pop's up a warning dialog, e.g.:
but clicking continue will add the registry values successfully and the app functions normally.
What can i do/or add changes in my code to make the dialog box disappear or can i do it in a better way?
The app requires Admin Privileges
here's the git repo of the app
here's the method:
public void SetMac(string macAddress)
{
const string Name = #"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}";
using (RegistryKey key0 = Registry.LocalMachine.OpenSubKey(Name, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl))
{
string[] x = key0.GetSubKeyNames();
foreach (string name in x)
{
var var1 = Registry.LocalMachine.OpenSubKey(Name,RegistryKeyPermissionCheck.ReadWriteSubTree,RegistryRights.FullControl);
var v = var1.OpenSubKey(name, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
var z = v.GetValue("DriverDesc");
if (comboBox1.Text == z.ToString() )
{
v.SetValue("NetworkAddress",comboBox2.Text);
MessageBox.Show(z.ToString());
}
v.Close();
var1.Close();
}
key0.Close();
}
}
You need to run your app under elevated privileges, see Requested registry access is not allowed.
The problem here is that the user does not have permission to open the target key for writing. As abatishchev has already suggested, you need to run the application elevated so that the user actually has Administrators group membership when the code is executed.
The reason that this looks like a CAS permission error is a design flaw in the RegistryKey.OpenSubKey method. It ought to throw an UnauthorizedAccessException when the target key cannot be opened for writing due to inadequate user permissions, but it actually throws a SecurityException instead. The problem ends up appearing to be due to insuffience CAS permissions when it is really the user, not the code, that lacks permissions to edit the key.