FileSystemWatcher on folder on desktop (or C drive) - c#

I am creating a winforms project which checks files in folder. It only works when new file put in the folder. I am using FileSystemWatcher. It works fine on D drive but fails on C drive.
I gave EVERYONE full privilige on that folder
I tried publishing it with click once for full trust application. But it failed also with published edition
Tried to run exe file and visual studio as administrator. Nothing changed
Tried absolute path and Extra filters.
It does not raise any errors. Simply does nothing.
Non Working Code
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
teklifwatcher.Path = desktop+"\\XMLTeklif";
teklifwatcher.NotifyFilter = NotifyFilters.LastWrite;
teklifwatcher.Filter = "*.xml";
teklifwatcher.Changed += new FileSystemEventHandler(TeklifXML);
teklifwatcher.EnableRaisingEvents = true;
private void TeklifXML(object sender, FileSystemEventArgs e)
{
//dostuff
}

I solved this problem on my own. I assume filesystemwatcher can't watch c: drive files directly. Because of the security reasons.
But we can use Program Files (X86) folders just like any other application.
Anyone who have similar problems just use filesystemwatcher on a folder at program filex(x86). And give permissions to that folder. Voila! It works

Related

How to determine if C# executable is being run from zip file?

I'm trying to ensure that users of my C# .NET Core program always unzip it before running, however, I can't seem to find a good solution for this.
I tried using Assembly.GetExecutingAssembly().Location and checking if it contained Temp but it did not work as intended. My understanding is that when running an executable within a zipped file, Windows will automatically unzip (?) to a temp directory and then proceed.
Any ideas on how to go about doing this?
Thanks!
One solution might be that you put another file beside the exe file inside the zip file and make the exe find for this file in the same location of the exe.
When an exe is executed from inside a zip, the unzip program will unzip the exe but not the other file and checking for this file you can test whether just the exe was unzziped or if the whole files where unzipped and the guess it was installed.
(Anyway, I agree with Ian Kemp, as it seems to be an XY problem)..
I can think of two checks that will work in many cases. Obviously, these checks are not bullet-proof.
Most .zip viewers will extract the clicked .exe in a temporary folder.
Windows Explorer zip folder view runs the .exe from a temporary folder and sets the ReadOnly attribute.
Sample app
using System;
using System.IO;
namespace SimpleApp
{
class Program
{
private static bool IsLikelyRunFromZipFolder()
{
var path = System.Reflection.Assembly.GetEntryAssembly().Location;
var fileInfo = new FileInfo(path);
return fileInfo.Attributes.HasFlag(FileAttributes.ReadOnly);
}
private static bool IsRunFromTempFolder()
{
var path = System.Reflection.Assembly.GetEntryAssembly().Location;
var temp = Path.GetTempPath();
return path.IndexOf(temp, StringComparison.OrdinalIgnoreCase) == 0;
}
static void Main(string[] args)
{
var isTemp = IsRunFromTempFolder();
var isZip = IsLikelyRunFromZipFolder();
Console.WriteLine($"Run from TEMP folder? {isTemp}");
Console.WriteLine($"LIKELY run from Windows Explorer ZIP folder? {isZip}");
Console.ReadKey();
}
}
}
I disagree with the sceptics in this thread. Running an exe from a "zip folder" in Windows Explorer is indeed a common source of error. By showing a warning, inexperienced users could get some immediate advice.

Specify Working directory for ocx files in C# utility

I have created an Utility.exe using C# which allows users to choose one of the multiple versions of an application. The user runs the Utility.exe and clocks on one of the version buttons in the Utility window which triggers a batch file for that version and then the respective application.exe.
The problem I am facing is after the Application.exe is triggered. The user logs into the application but gets the error Database Handle is Invalid.
But, when the user goes to the Application version folder and runs the batch file and then launches the application, it works fine.
My assumption is that when we trigger the batch file through the utility.exe, it does not discern the file path for the OCX and DLL files and thus does not register them properly.
A workaround is to specify the file path for the OCX and DLL files in each of the version batch files on each of the user's desktops.
Is there a way I can specify the file path in the utility code (C#) for the OCX and the DLL files mentioned in the batch file?
EDIT: I tried using process.StartInfo.WorkingDirectory as suggested by Dave but still getting the same issue.
private void button1_Click(object sender, EventArgs e)
{
string batDir = string.Concat(#"C:\Program Files (x86)\Blah\BlahBlah\batch.bat");
Process proc1 = new Process();
proc1.StartInfo.FileName = batDir;
proc1.StartInfo.WorkingDirectory = #"C:\Program Files (x86)\Blah\BlahBlah";
proc1.StartInfo.CreateNoWindow = false;
proc1.StartInfo.Verb = "runas";
proc1.Start();
proc1.WaitForExit();
string exeDir = string.Concat(#"C:\Program Files (x86)\Blah\BlahBlah\application.exe");
Process proc2 = new Process();
proc2.StartInfo.FileName = exeDir;
proc2.StartInfo.CreateNoWindow = false;
proc2.Start();
}
Hopefully, I have been able to articulate my problem.

c# custom action is not deleting particular file

I have found that on un-installing myproject setup installer is removing all files but not one conn.cnf file .I want it to be removed too . so I used custom Actions installer class.but it is not removing that file .
this is my code
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Uninstall(IDictionary savedState)
{try
{
base.Uninstall(savedState);
if (System.IO.File.Exists(Application.StartupPath + "\\Conn.cnf"))
System.IO.File.Delete(Application.StartupPath + "\\Conn.cnf");
}
catch (Exception es) { MessageBox.Show(es.Message); }
}
i have tested if cursor is going in this block or not, by putting a messageBox. which is being execute on un-installation .I have also checked file name ,am i trying to delete file in a wrong way ? Help me. thanks
This is quite difficult to find out the application path. Actually its not an application path its installation directory. When you try to find Application path using Application.StartupPath. You may get C:\System or something like that directory. Because your application is using Windows Installer to uninstall and install the application from the computer and the Windows Installer is installed in System folder. You should try to find Target Directory instead of Application or Executable path.
You can get the Target Directory from the Context Parameter like this.
string targetFolder = Context.Parameters["TARGETDIR"];

How to change permissions of a folder inside System32 in C#?

I need to programmatically remove "create file" and "create directory" permissions on a directory inside System32 directory for a group "NT AUTHORITY\\INTERACTIVE".
To do this, I wrote following code:
string windir = Environment.GetEnvironmentVariable("systemroot");
string redirectionFolder = (windir + "\\System32\\Tasks2");
MessageBox.Show(redirectionFolder);
FileSystemAccessRule Tasks = new FileSystemAccessRule("NT AUTHORITY\\INTERACTIVE", FileSystemRights.CreateDirectories | FileSystemRights.CreateFiles, AccessControlType.Deny );
DirectorySecurity dirSecurity = new DirectorySecurity(redirectionFolder, AccessControlSections.Group);
dirSecurity.AddAccessRule(Tasks);
Directory.SetAccessControl(redirectionFolder, dirSecurity);
When I run this code on a folder C:\Tasks2, it works.
But when I run it on C:\Windows\System32\Tasks2, I get the System.IO.DirectoryNotFoundException exception. Running the app as administrator doesn't help.
What can I do in order to change permissions of a directory inside System32 directory in C#?
Assuming that C:\Windows\System32\Tasks2 really does exist, the most likely explanation is that you are being caught out by the file system redirector. You have a 32 bit process and the file system redirector converts system32 into SysWOW64. And so whilst you think you are looking for C:\Windows\System32\Tasks2, you are actually looking in C:\Windows\SysWOW64\Tasks2.
Compile your program as 64 bit. Or use C:\WINDOWS\SysNative.

Programmatically-created subfolder not visible in Windows Explorer

I'm trying to add a subdirectory to an existing path.
Win-7 64, Intel SSD
Logged into company domain as a user with admin priv, but not as "Administrator"
Visual Studio 2008, launched normally (not "Run as Admin")
Here's MyApp (WinForms, Debug, x86):
[STAThread]
private static void Main(string[] args)
{
string p = #"C:\ProgramData\MyCompany\MyApp";
Directory.CreateDirectory(p);
string f = "a.txt";
string fullPath = Path.Combine(p, f);
File.WriteAllText(fullPath, string.Empty);
Directory.Delete(p);
As expected, the last line throws IOException: "The directory is not empty". Should mean the subdir and file got created.
Problem: Windows Explorer does not show the MyApp subdir (even after refresh, type path in address bar, close/reopen, or reboot).
C:\ProgramData\MyCompany\ was created by another application's installer; Windows Explorer says its current owner is System.
Used same IDE to create a console app (Debug, x86), copied the above lines and ran; Windows Explorer was happy to show me DigitalTestApps and the file inside.
If I do any one of the following to MyApp, the problem goes away (i.e. Windows Explorer shows me the "MyApp" subdir and the file inside):
Build as x64
Launch Visual Studio using "Run as Admin"
Use any name other than "MyApp" (but I need to use MyApp for legacy reasons)
What could be causing this?
#dtb was too humble (or busy) to repost his comment (which solved my problem) as an answer, so I'll copy his comments here to make it easier for others to see how this turned out:
"Check if you can find your directory & file somewhere in C:\Users\JimC\AppData (Folder virtualization).
related: Why Virtualization on ProgramData folder in MS Vista?"
So here is what I did after reading his advice:
I deleted the virutalized directory from under C:\Users and it started working fine. Not sure how it got created in the first place, but seemingly, while it exists, attempts to create the directory where I was expecting it finds the virtualized one instead.
Thanks again dtb.

Categories