C# Application autorun exception - c#

I wanted to add my C# application to Windows autorun programmatically and read somewhere that code below would do the trick:
var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("MyApplication", System.Reflection.Assembly.GetEntryAssembly().Location);
When I restarted my computer, application's splash screen showed up but after a few seconds the application crashed and I saw this:
an unhandled microsoft .net framework exception occured
Could you give me some clues where to look for source of the problem?
EDIT :
I ran debugger and that's what I found out (XamlParseException):
{"'The invocation of the constructor on type 'MyApplication.GUI.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'."}
And inner exception message (System.UnauthorizedAccessException):
{"Access to the path 'C:\\Windows\\system32\\db.db' is denied."}

This is a bug in your code, you are using a relative filename instead of a full path. In other words, "db.db" instead of "c:\foo\bar\db.db". You'll now have a big dependency on the default directory of the program. This will work just fine in Visual Studio when you debug and test your app, the default directory will be the bin\debug directory of your project. You'll have no trouble writing to that directory.
But will not work when your program is launched by Windows, the default directory of your program will now be the default Windows directory, c:\windows\system32. Programs do not have write access to that directory, it is protected by UAC.
Fix the bug by specifying the full path to the file. You'll want to use Environment.GetFolderPath() to obtain a good directory, that should almost always be SpecialFolder.ApplicationData. Use the Path.Combine() helper method to construct the path.

Related

windows installer cannot access directory

I am trying to run some custom actions code for windows service (the service is LocalSystem account) with windows service installer and i get the following error message:
error message while installing MSI:
Error 1001. An Exception occurred in the OnAfterInstall event handler
of System.ServiceProcess.ServiceInstaller. --> Access to the path XXX
is denied.
this code is throwing the error:
protected override void OnAfterInstall(IDictionary savedState)
{
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
System.IO.File.WriteAllText(path, "test");
}
At the code i am trying to access the service .exe directory so i could delete the files created there
My goal is to make a custom action for the install/uninstalling process. i want to delete files that was created after installation like logs and configuration file.
Thanks
You are trying to write text to a directory instead of a file. The variable "path" is returned from Path.GetDirectoryName() which is a directory. In the next line, you are trying to do File.WriteAllText() to this variable, thus the error.
Path.Combine: As already mentioned by others, you need to specify a proper full path (path and file name). Maybe use Path.Combine? For example:
System.IO.File.WriteAllText(Path.Combine(path, "filename.txt"), "test");
Alternatives: I am not a .NET expert, and I don't use managed code custom actions. However if they are DTF based I am not sure if they have any clunk with regards to current directory or executing directory. Listing some further links:
Adding a note about: Environment.SpecialFolder (get all kinds of special folders) and Environment.CurrentDirectory (get current directory).
Reflection might be better, but check this answer: How to get execution directory of console application (all answers). There is also: AppDomain.CurrentDomain.BaseDirectory: Getting the absolute path of the executable, using C#?.
And then there is the suggestion to use GetEntryAssembly: C# – Getting the Directory of a Running Executable.
Directory.GetCurrentDirectory Method.

C# File Not Found For Custom Font in Visual Studio Designer

I'm relatively new to C#, so pretty much I have a folder included in my WinForms project that contains a custom font. The font works absolutely fine upon launch of the application, but in the actual designer on Visual Studio itself, the custom control can't be loaded (as the path I'm using is different when in the designer). Here is the code I use to locate the font from the resources folder:
string leadDirectory = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources" + Path.DirectorySeparatorChar + "Roboto-Regular.ttf");
The directory which is used in the designer is "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Resources\Roboto-Regular.ttf", and obviously it throws a file not found exception in the method.
Any help would be appreciated!
You are not opening the directory you think you are opening. Check in debug mode what System.Windows.Forms.Application.StartupPath actually is.
To fully understand what goes wrong here, you should understand how running programs from the command prompt work. You have the command prompt, and on that prompt, you see your "current path" is set to a certain directory. Normally, this indicates you want to do stuff in that particular directory, but you can launch a program that is anywhere on your system by giving the full path to launch. However, this will not make your command prompt switch to the path of that launched application. You will still remain in that same folder, despite running a program that is located somewhere else. This folder is the "startup path" that you are using. As you can imagine, it has no relation at all to where you are trying to look for that Resources folder.
Despite having evolved to a graphical user interface, the way programs launch still works the same way as it did in DOS, so this distinction remains.
In Windows Forms, you can use Application.ExecutablePath to get the full path and filename to your exe file, so if you use Path.GetDirectoryName() on that, you have the base path you want. In case your program would not be a WinForms application, you can instead use Assembly.GetExecutingAssembly().Location, from the System.Reflection namespace.

Why does relative path of project files auto-resolve to c:\windows while executing the build in release mode?

So, I have completed a C# console application using Microsoft Visual Studio 2012.
I have a local file within the project folder. Within my code, I have performed a log writing operation by assigning the relative path of this file to a string variable. The file was created during the first build/run and then appended with information during further runs.
string rpath = "..\\LogFile2.txt";
I built this project in debug mode and ran it. During this run the rpath is correctly identified as
c:\project_app_folder\bin\LogFile2.txt
However, while building this project in release mode and then scheduling the .exe file to run at a particular time in the windows task scheduler, I get a run-time error saying
Could not find a part of the path 'C:\local\pic'.
How do I resolve this? I want the temporary folders or text files created during run time to be part of my project folder/package?
Please also note , I cannot put absolute paths as this code will have to be packaged and sent to another user and that user may chose to store the program in a location he/she sees fit.
This issue is not because of release mode, when the scheduler invokes the program the working directory will be different as #Damien_The_Unbeliever said. you can use the "start in" option when you specify your action, as your release directory.
The "start in" is mainly to make sure that if you have relative paths
in the task to run, it understands which directory to use.

Could not write to output file -- Access is denied

I recently switched computers and copied all my projects over to my new local drive. I reformatted the computer I'm on now so it was pretty much a clean machine. Everything seemed to be working fine, but when I opened one of my projects that I had been running from my old machine, it would no longer compile, and I get the following error message:
Could not write to output file 'c:\Users\user\Documents\Projects\RegressionWeb\OnetouchUpload\obj\debug\OneTouchUpload.dll' -- 'Access is denied.'
I'm getting an error like that for each project I have in my solution. I'm also getting this error:
Unexpected error creating debug information file 'c:\Users\user\documents\projects\RegressionWeb\RegressionWeb\obj\Debug\RegressionWeb.PDB' Access is denied
I've searched high and low, and the only similar issues I could find online related specifically to ASP.NET and IIS, neither of which has anything to do with my project (My projects are class libraries of mostly NUnit tests with some support classes).
I am the administrator on my local machine. I have already taken ownership of every file in the project using takeown /f .\RegressionWeb /r /d y and also tried to ensure that nothing had a status of Read-only, but the following file threw an error when I tried changing the read-only property of it's parent folder:
An error occurred applying attributes to the file:
C:...\Regressionweb.sln.DotSettings.user
Access is denied
Basically this project was working perfectly and had no errors from my old computer. After copying over everything, this DotSettings.user file will not be modified, and Visual Studio can't write to any of the dll files. I'm sure the answer must lie in a Visual Studio setting somewhere. Any and all suggestions would be greatly appreciated.
I think Karl has it right. I had a similar situation once, and what I did was delete the file in question, clean the solution, and then rebuild. If the project needs that file it should recreate it; in my case it didn't need it because it never recreated it, but the project ran just fine.
One other thing I would recommend; you may be selecting the read-only attribute of the parent folder off and selecting this setting to recurse through all sub-folders and files, but that doesn't mean that's what's happening. For all your sub-folders and files (especially the ones that are cropping up as errors) inspect each one individually and make sure the read-only attribute is off.
My money is on your files are read-only. Verify they are read-only and change them or add your files to a source control system and let them get handled by that.
I was able to get this working by closing Visual Studio and then opening it again, but being careful to run Visual Studio "As Administrator". To do this, from the Start menu, right click on Visual Studio and choose "Run as Administrator".
it seems that the same error is sometimes displayed when the app pool user doesn't have access to the %TMP%/%TEMP% folder.
You'll need to grant IIS_IUSRS read and modify access over the temp folder of the user the app pool is running as.
This could either be the temp folder in the app pool user's profile, e.g. c:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp, or the system temp folder at c:\windows\temp.
See if it is related to this:Could not write to output file - Access is denied
. That would be a bit of a bugger to track down. In this case the project is self-referencing the dll and preventing access to the file.
This has a very simple solution, you just have to make sure that your directory name(folder name) is not the same as your file name. I created a folder by the name Pointers, my code was in a file pointers.cpp. When I compiled the code it kept showing the same error. I just had to change the directory or folder name to L1_pointers. You can change it to anything you want and it worked.

XML file couldn't be detected after windows service setup

I have created a windows service. I do the setup of the service using the windows installer.
I have one XML file like a config file. Whenever i debug windows service with attaching the debug project it works fine. But after the installation i can see the event saying couldn't find the example.xml file in C:\Windows\system32. It's a repeating problem. Can anyone tell me whats going on with this. Or any suggestions?
This isn't an installer problem. Windows Services are always started with System32 as the current directory. Add this line to the Main() method in your Program.cs prior to firing up any services.
Environment.CurrentDirectory = new FileInfo(Assembly.GetExecutingAssembly().FullName).DirectoryName;
Most likely file is just not where you are looking for it.
Chances are that your code looks in "current working folder" which during debugging in VS is the same as application, but in case of starting as service/from command line is different.
Make sure your code loads file from location you expect the file to be (i.e. next to the application), but not from some relative path (like "myfile.xml").
Why are you saving stuff in the Windows folders? Unless there's a really good reason to do so, this is bad. Install your config in the same place that your app is running and get the file path with:
var folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var configPath = Path.Combine(folderPath, configFileName);
The issue is that your service is not running as Administrator. If the service is not running as Administrator, then it won't be able to read the files under system32 folder.
Change the service properties to run as Administrator. That should fix the issue.

Categories

Resources