windows installer cannot access directory - c#

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.

Related

GetCurrentDirectory() returns local path after deployed on server

Requirement:
In my .Net Core console application, I use Directory.GetParent(Directory.GetCurrentDirectory()) to retrieve the current parent folder of where my template file is stored.
Issue:
After deploying on server, when I manually run the exe by double clicking it works fine. But when I try to run it with batch or task scheduler, the above statement return by local computers path, instead of the path on server.
Server Details:
OS: Windows Server 2012 R2 Standard
Error Stack:
Error Message : Could not find document StackTrace : at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(String path, Boolean readWriteMode)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(String path, Boolean isEditable, OpenSettings openSettings)
at CV_Export.Program.SearchAndReplace(String TemplatePath, String NewDocumentPath) in C:\Siddharth\Demo Codes.Net Core Demo\CV Export with API\CV_Export\Program.cs:line 163 TIme : 7/21/2021 4:41:53 PM
This error was generated when I tried to run the exe through batch and the path on the error is of my local system.
Thank you in advance for your help.
By using Directory.GetParent(App.Domain.CurrentDomain.BaseDirectory) you can provide the relative path to the base directory of your application.
When you are using Directory.GetCurrentDirectory() you are providing the path from where you are running the application, which can be for instance C:\Windows\System32, and the parent directory will be C:\Windows instead of the parent directory of your .net application.
GetCurrentDirectory()
Gets the current working directory of the application.
The working directory is an environment concept and is affected by where and how the application is executed, not where the file is logically located.
You can avoid this by using App.Domain.CurrentDomain.BaseDirectory() instead, that will force lookups for these resources to always be relative to the executable.
BaseDirectory vs CurrentDirectory in C#
NOTE:
In many cases it is still beneficial to use GetCurrentDirectory() as that allows your executable to be installed in a central location, but to allow different user or security contexts to access a different set of files.
If you stick with GetCurrentDirectory() here's some advice on how to configure it from the calling context:
Batch Files / Scripts
When executing from a batch file, the current environment context will default to be operating in the working directory that applies to the batch folder.
So in your batch, you need to change the working directory to the folder the exe is in first, if you used a UNC path or full path to access the exe, then it won't be running in that directory, instead if you use a cd command to change the directory first that will often do the trick.
Task Scheduler
Specifying the running directory for Scheduled Tasks using schtasks.exe
If you are using the GUI, then you can deliberately set the working folder via Start In: https://stackoverflow.com/a/27401164/1690217
Shortcuts
Similar to Scheduled Tasks, in shortcuts you can also specify the working directory:

Change download folder [duplicate]

I am trying to create new file in visual studio 2012
fileStream = new FileStream("google_com.txt", FileMode.CreateNew);
But i keep getting this error
Access to the path 'C:\Program Files (x86)\IIS Express\google_com.txt' is denied.
Plz help to fix this poblem.
Solutions:
Put a specific location for google_com.txt file. like C:\google_com.txt. Actually it is not allowing to create the file in default location(inside program files) as it might not have the proper privilege.
If you want to create the file in default location(inside program files) run Visual Studio as Administrator.(R-Click-> Run as Administrator).
Run Visual Studio as Administrator
You can't write to the Program Files folders on Windows Vista or later unless you're running elevated/as an administrator.
You should be writing to the application's App_Data folder if you need to write anywhere. Look into using Server.MapPath().
If this is in a web app, the file will be created in the application's root, which in this case is your iis express directory. Run Visual Studio as Administrator, or change the location of the file by specifying an explicit path.
Official Microsoft response:
Issue occurs because of missing permissions on a local resource that
the ASP.NET application tries to access If you are unable to get a
clear description of the problem because of a custom error message,
run FileMon and reproduce the problem. Stop and save the capture as
FileMon.xls and open the file in Microsoft Excel. On the Data menu,
click Filter, and then click AutoFilter to use the filtering
capabilities of Excel. Now select the drop-down list in column F and
look for "ACCESS DENIED" errors.
A sample FileMon output is shown below. 10381 1:01:11 PM w3wp.exe:2320
OPEN C:\winnt\microsoft.net\framework\v1.1.4322\Temporary ASP.NET
Files\sessiontest\8832e585\275ec327\global.asax.xml ACCESS DENIED NT
AUTHORITY\NETWORK SERVICE As you can see from the filtered results,
we have narrowed down the cause of the problem. FileMon shows that the
NT AUTHORITY\NETWORK SERVICE account is missing NTFS permissions on
the C:\Winnt\Microsoft.net\Framework\v1.1.4322\Temporary ASP.NET Files
folder. This should be straight forward to fix. For more information
about using FileMon to troubleshoot ASP.NET, click the following
article number to view the article in the Microsoft Knowledge Base
https://support.microsoft.com/es-ve/help/910449/troubleshooting-common-permissions-and-security-related-issues-in-asp
Try this:
Server.MapPath("~/ FolderName / google_com.txt ")

C# Application autorun exception

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.

How come my Windows Service cannot access a folder with files in them?

I have setup a Console, Library, and Service project. The Library project loads up files in a folder and stores the text in variables.
The console project will then manipulate those variables. I am able to run the Console project successfully and it loads the files without a problem. The files are set to Copy Always in the DLL and are specified as Content for the Build Action.
When I try to run the exact same code in the service.
File.ReadAllText(#"MyFolder\SomeFile.txt");
It throws the following exception.
The type initializer for 'MyLibrary.Data.ReadFiles' threw an exception.
I am using the Setup Project type to create the installer. After the service installs the folder MyFolder does exist in the Application Folder of the service, as well as the files. What else could be causing my problem for the service not being able to read those files?
EDIT 1
public class ReadFiles {
public static string DataFile = File.ReadAllText(#"MyFolder\SomeFile.txt");
}
The service account that you're running the Windows service under, doesn't have rights to read from the location you're trying to access. The error you're seeing has to do with the fact that the code you showed likely exists in the construction of the type ReadFiles.
Was facing similar issue in one of the windows service for running node js application, for sending emails.
It was running fine when we run from the same directory, but running same application as windows service was having issues and couldn't send emails. Comment from #meanbunny did help, so adding it as an answer.
Windows service can't access the directory/files if they are mentioned in the code as relative path, better use the absolute path or be more flexible as #Mike mentioned in his comment to use app.config for each service.

Directory Rename Exception in C#

When I try to rename a Directory using the following code:
try
{
System.IO.Directory.Move(oldPath, newPath);
}
catch (System.IO.IOException e2)
{
Console.WriteLine(e2.Message);
}
I get the following exception: The process cannot access the file because it is being used by another process.
I don't understand why it says "file" in the first place.
Also, the directory is empty. What file is it referring to?
Lastly, how to manage to rename the Directory without any exceptions?
UPDATE: I guess I found the reason for the exception, it is because I am trying to rename the file/folder names of files/folders situated in the Google Drive. The Google Drive application is the other process using it! Any solutions to rename a folder in the Google Drive? But the weird thing is that I don't get this exception when I try to rename files located in the Google Drive through C#.
Thanks!
Your folder seems to be in use by another process. Try to close your explorer or other programs, that use that folder. If nothing help - try to restart your machine. If those won't help - consider using Unlocker to free folder from usage of another process. Note that it would be weird, if non-system folder is occupied after restart of the machine
It says "file" because the underlying commands are probably using a
generic move command for both directories and files and the
localized error string contains the word file.
Even if a directory is empty, it can be locked for any edits if you have it "open" in an application (do you have explorer Windows open in the directory, is the command prompt current directory set to the one you want to move/delete)?
Unfortunately there's not much you can do unless you want to start killing offending processes programmatically.
You can use Process Explorer to find the process that has a lock on that folder. See http://windowsxp.mvps.org/processlock.htm for more info.
1 Verify that newPath already does not exist
http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx
2 Verify that your directory does not contain opened file

Categories

Resources