StreamWriter Access Denied on Windows Startup [duplicate] - c#

I am using registry key to set my application to load on Windows Startup(after a user login).
My Code:
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
RegKey.SetValue("AppName", "\"" + #"C:\Users\Name\Desktop" + "\"");
RegKey.Close();
So with this code, my application load at startup, however the working directory is
C:\Windows\System32
Does anyone know why ?
This does not work for me because that program needs couple of files within the same directory as that one to operate. If the program loaded on my chosen directory("C:\Users\Name\Desktop") then the problem would not exist.
Anyone has any suggestion for this ?

Directory.SetCurrentDirectory() can be used to set your working directory when the app starts. EXE path can be retrieved using Application.ExecutablePath.
Put them together:
var fi = new FileInfo(Application.ExecutablePath);
Directory.SetCurrentDirectory(fi.DirectoryName);

I've figured out a cheap trick on how to accomplish this.
When your application starts up, Read the registry again to get your application's start-up path(the one you intended).
For example: Appl1 has a startup path of "C:\Users\Name\Desktop\App1.exe".
Once you read the registry for that path, set that as current directory.
Something like this:
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);
string Path = RegKey.GetValue("App1.exe").ToString();
Path = Path.Replace(#"\App1.exe"", ""); // Now it's a valid directory.
Directory.SetCurrentDirectory(Path);
This worked for me but if anyone has a better method, I would love to hear them.

Related

C# Folder browse Dialog not showing Network shared folders win10

I have created an application(windows) compiled with .NET 4.6.1 and used the FolderBrowserDialog object. When a button is pressed I execute this code:
FolderBrowserDialog folderbrowserdialog = new FolderBrowserDialog();
folderbrowserdialog.Description = "Custom Description";
if (folderbrowserdialog.ShowDialog() == DialogResult.OK)
{
filePath = folderbrowserdialog.SelectedPath ;
}
what i get from the folderbrowserdialog(like foto)
however ,the folder browserdialog is not showing the networks shared folder(that the purpose of my app) otherewise just the pc folders.
but what i want to get it is the network shared folders which could i also access from windows 10 like foto here:
notes to be marked:
i could not use the open file dialog cause i need the folder location.
i desgined the Appto be opened just like admin by adding manisfest so the app is always starting like admin.
the app should be comptiable with windows 10,7
note i know that i could try setting this registry option (could be broken in Win10):
HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System
EnableLinkedConnections=1
but it does not make a sense to add this registry by every customer PC
so is there any tipps to show the network shared folders in FolderBrowserDialog ?
Finally after reading many topics i found that the only solution is to add a Registry key programmatically so here how to add specfic C# Registry Subkey with dword value:
i wrote a method wich could all use it
just to let you know after using it you have to restart the device after it ,it will work ;)
public void ConfigureWindowsRegistry()
{
RegistryKey localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); //here you specify where exactly you want your entry
var reg = localMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
if (reg == null)
{
reg = localMachine.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
}
if (reg.GetValue("EnableLinkedConnections") == null)
{
reg.SetValue("EnableLinkedConnections", "1", RegistryValueKind.DWord);
MessageBox.Show(
"Your configuration is now created,you have to restart your device to let app work perfektly");
}
}
I had the same issue. The reason of the problem: I was using as an Administrator. The mapped drives are related to the user, so I tried to use as an normal user and I could see the mapped drives.

c# retrieve file/folder path from selected file/folder in Context Menu Windows Explorer

I'm trying to implement an option in the context menu of Windows Explorer for any file and any folder.
I have accomplish this by writing into regedit.
Using Microsoft.Win32;
...
RegistryKey key;
// Register to any file
key = Registry.LocalMachine.CreateSubKey(#"SOFTWARE\CLASSES\*\shell\MyProject");
key = Registry.LocalMachine.CreateSubKey(#"SOFTWARE\CLASSES\*\shell\MyProject\command");
// Register to folder
key = Registry.LocalMachine.CreateSubKey(#"SOFTWARE\CLASSES\Folder\shell\MyProject");
key = Registry.LocalMachine.CreateSubKey(#"SOFTWARE\CLASSES\Folder\shell\MyProject\command");
// Default value points to the app
key.SetValue("", Application.StartupPath + #"\MyProject.exe");
key.Close();
The application opens as I want, however I have no clue how to grab the path of file/folder that was selected in the context menu. How can I do this?
Change the value of the registry key to
key.SetValue("", Application.StartupPath + #"\MyProject.exe %1");
So %1 is replaced with the selected file/folder. In your main method you can access this via:
static void Main(string[] args)
{
Console.WriteLine("Selected file/folder: {0}", args[0]);
}
Unfortunatly this will not work for multi-selection. Placing %2 etc is of no use. If multiple files or folders are selected your application gets called for each of them seperatly.
The answer of René Vogt is great only this line:
key.SetValue("", Application.StartupPath + #"\MyProject.exe %1");
should be:
key.SetValue("", Application.StartupPath + #"\MyProject.exe \"%1\"");
Without the quotation marks the args[] array contains multiple strings when the directory or file path contains whitespaces.

Starting application on start-up, using the wrong path to load

I am using registry key to set my application to load on Windows Startup(after a user login).
My Code:
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
RegKey.SetValue("AppName", "\"" + #"C:\Users\Name\Desktop" + "\"");
RegKey.Close();
So with this code, my application load at startup, however the working directory is
C:\Windows\System32
Does anyone know why ?
This does not work for me because that program needs couple of files within the same directory as that one to operate. If the program loaded on my chosen directory("C:\Users\Name\Desktop") then the problem would not exist.
Anyone has any suggestion for this ?
Directory.SetCurrentDirectory() can be used to set your working directory when the app starts. EXE path can be retrieved using Application.ExecutablePath.
Put them together:
var fi = new FileInfo(Application.ExecutablePath);
Directory.SetCurrentDirectory(fi.DirectoryName);
I've figured out a cheap trick on how to accomplish this.
When your application starts up, Read the registry again to get your application's start-up path(the one you intended).
For example: Appl1 has a startup path of "C:\Users\Name\Desktop\App1.exe".
Once you read the registry for that path, set that as current directory.
Something like this:
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);
string Path = RegKey.GetValue("App1.exe").ToString();
Path = Path.Replace(#"\App1.exe"", ""); // Now it's a valid directory.
Directory.SetCurrentDirectory(Path);
This worked for me but if anyone has a better method, I would love to hear them.

Issue in accessing the registry programmatically

I have a issue reading a registry value programmatically using C#.
I looked into many sites and help but could not find any helpful.
I am able to access and read registry when I run VS in eleveated mode, but face issue when I run VS with out elevated mode.
Initially I started with the below code
byte[] val = (byte[])Registry.GetValue("HKEY_LOCAL_MACHINE\\Software\\MyServices\\Identity\\ASPNET_SETREG", "ValueName", 0);
This worked fine with elevated mode, but fails in non elevated mode.
Placed the attribute on top of the function
[RegistryPermissionAttribute(SecurityAction.Demand,Unrestricted=true)]
This did not help. Then Tried
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.AllFlags)]
Still did not work.
Now I Tried the below code...
RegistryKey key = Registry.LocalMachine;
RegistrySecurity rs = new RegistrySecurity();
rs = key.GetAccessControl();
string user = "DomainName\\Username";
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.ReadKey,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Allow));
key.SetAccessControl(rs);//Exception: "Attempted to perform an unauthorized operation."}
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG");
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", false);
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree);
RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadPermissions);
Commenting SetAccessControl and use any of the OpenSubkey option, I get Exception: "Requested registry access is not allowed."
I am badly stuckup and unable to proceed.
private RegistryKey keyR = Registry.CurrentUser.OpenSubKey("Software\\YourKey",true);
private RegistryKey keyW = Registry.CurrentUser.CreateSubKey("Software\\YourKey");
public string version
{
get { return keyR.GetValue("VERSION", "", RegistryValueOptions.DoNotExpandEnvironmentNames).ToString(); }
set { keyW.SetValue("VERSION", value, RegistryValueKind.String); }
}
I am using windows registry in this way. No problem...
The windows registry is basically a structured file system, and has permissions for keys and values.
You do not have the permissions set correctly on ...\MyServices\ or deeper keys - you have no permission to access those from your unprivileged process.
Either:
Those keys should be readable by anybody, so you should change the permissions to make them readable by everybody. Or -
Those keys were intentionally restricted for a good reason, and so they should not be readable by everybody, in which case your program should always run elevated.

Error in Process.Start() -- The system cannot find the file specified

I am using the following code to fire the iexplore process. This is done in a simple console app.
public static void StartIExplorer()
{
var info = new ProcessStartInfo("iexplore");
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
string password = "password";
SecureString securePassword = new SecureString();
for (int i = 0; i < password.Length; i++)
securePassword.AppendChar(Convert.ToChar(password[i]));
info.UserName = "userName";
info.Password = securePassword;
info.Domain = "domain";
try
{
Process.Start(info);
}
catch (System.ComponentModel.Win32Exception ex)
{
Console.WriteLine(ex.Message);
}
}
The above code is throwing the error The system cannot find the file specified. The same code when run without specifying the user credentials works fine. I am not sure why it is throwing this error.
Can someone please explain?
Try to replace your initialization code with:
ProcessStartInfo info
= new ProcessStartInfo(#"C:\Program Files\Internet Explorer\iexplore.exe");
Using non full filepath on Process.Start only works if the file is found in System32 folder.
You can't use a filename like iexplore by itself because the path to internet explorer isn't listed in the PATH environment variable for the system or user.
However any path entered into the PATH environment variable allows you to use just the file name to execute it.
System32 isn't special in this regard as any directory can be added to the PATH variable. Each path is simply delimited by a semi-colon.
For example I have c:\ffmpeg\bin\ and c:\nmap\bin\ in my path environment variable, so I can do things like new ProcessStartInfo("nmap", "-foo") or new ProcessStartInfo("ffplay", "-bar")
The actual PATH variable looks like this on my machine.
%SystemRoot%\system32;C:\FFPlay\bin;C:\nmap\bin;
As you can see you can use other system variables, such as %SystemRoot% to build and construct paths in the environment variable.
So - if you add a path like "%PROGRAMFILES%\Internet Explorer;" to your PATH variable you will be able to use ProcessStartInfo("iexplore");
If you don't want to alter your PATH then simply use a system variable such as %PROGRAMFILES% or %SystemRoot% and then expand it when needed in code. i.e.
string path = Environment.ExpandEnvironmentVariables(
#"%PROGRAMFILES%\Internet Explorer\iexplore.exe");
var info = new ProcessStartInfo(path);
Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message
I.e. this causes an issue with Process.Start() not finding your exe:
PATH="C:\my program\bin";c:\windows\system32
Maybe it helps someone.
I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.
In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.
So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.
I know it's a bit old and although this question have accepted an answer, but I think its not quite answer.
Assume we want to run a process here C:\Program Files\SomeWhere\SomeProcess.exe.
One way could be to hard code absolute path:
new ProcessStartInfo(#"C:\Program Files\SomeWhere\SomeProcess.exe")
Another way (recommended one) is to use only process name:
new ProcessStartInfo("SomeProcess.exe")
The second way needs the process directory to be registered in Environment Variable Path variable. Make sure to add it in System Variables instead of Current User Variables, this allows your app to access this variable.
You can use the folowing to get the full path to your program like this:
Environment.CurrentDirectory

Categories