How to check if you have permission to run a exe file - c#

C# .net Framework 4.0
Is there a simple way to check if you have the rights to run a file?
Before i do this:
//e.g. Press a button
....
string exePath = "D:\something\something.exe";
Process.Start(exePath);
i would like to check if the user has the rights to run that file?
When i'm making the function call Process.Start, windows popsup with a messagebox and says that i'm not authorized to run this application and this application is "D:\something\something.dat" and NOT .exe?

How to check if you have permission to run a exe file?
EAFP: It is Easier to Ask Forgiveness than it is to get Permission.
So, you can surround your code with try/catch block:
try {
Process.Start(path);
} catch (Win32Exception ex) {
// ...
}
and you can use Win32Exception.NativeErrorCode to access the numeric representation of the error code associated with this exception.
For more information about the error codes, check out Win32 System Error Codes.

Try surrounding Proccess.Start with try catch:
//e.g. Press a button
....
string exePath = "D:\something\something.exe";
try
{
Process.Start(exePath);
} catch (Exception e) {
// No permissions or file not found?
}
that'll do the job.

Related

I want to block all application in windows until user select option in combo box. Is it possible in WPF?

I am developing an application to capture production info. Application works fine. But there is a chance that user may ignore to login the application on system startup. Is there a way to compel the user to login to the application before startig their regular work?
You can try something like this.
If you call this method on load of your main screen of your application, it will run on startup automaticaly.
void InstallMeOnStartup()
{
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
Assembly curAssembly = Assembly.GetExecutingAssembly();
key.SetValue(curAssembly.GetName().Name, curAssembly.Location);
}
catch (Exception ex)
{
Log(ex.Message);
}
}

How to bypass FileNotFoundException

I have an text file which has some settings parameters for my project. My desktop layer reads this file. Therewithal , web layer's project read from from Server's MapPath.
FileStream has no operator to bypass an exception.I have tried to Exists control. But , i just need to bypass FileNotFoundException.
Place the code in a try catch.
try
{
//read
}
catch(FileNotFoundException ex)
{
//do logging for this silent catch
Console.WriteLine(ex);
}
How about this,
if (File.Exists(path)
{
// read file,
}
Another way,
if (File.Exists(path)
{
try
{
// read file,
}
catch (Some other exception related to file, read access violation, etc.)
{
handle exception,
}
}
How about checking the file exists or not?
if so, you can prevent throwing FileNotFoundException.
[Can not provide complete solution/feedback as we aren't sure about your actual implementation]
If(!File.Exists(<path_to_file>)
return;
// continue doing the rest only if file exists
Hope this helps. let us know if require more clarifications. It Would be nice if you could post your method implementation or at least a pseudo code for us to understand the actual problem you trying to solve.
Cheers,

How to save data to network path on .NET?

I'm really struggling with saving data to my local network NAS (a Synology DS214 if that matters).
I need to store some files in my network folders after creating them in another part of my program, but I haven't been able to handle the authentication/permissions properly.
My code atm is this:
WrapperImpersonationContext WIContext =
new WrapperImpersonationContext("\\\\DiskStation", "admin", "admin");
try
{
WIContext.Enter();
// code to select the final path simplified.
string fileName = "file.txt";
string originalPath = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
originalPath= Path.Combine(new string[] {originalPath, fileName});
string finalPath = "\\\\DiskStation\\Virtual\\DestFolder";
if (!Directory.Exists(finalPath))
{
// This goes well for whatever reason
Directory.CreateDirectory(finalPath);
}
finalPath = Path.Combine(new string[] {finalPath, fileName});
// This fails for wrong username/password
File.Move(originalPath, finalPath);
} catch (Exception ex)
{
// Exception showing simplified here
MessageBox.Show(ex.ToString());
throw;
} finally
{
WIContext.Leave();
}
The code used for the WrapperImpersonationContext I found here:
WindowsImpersonationContext made easy
As written in my code when I try to move the file I get an UnauthorizedAccessException: Access to the path is denied. I also tried to create a new file in the network folder with the same results.
While looking at the Michiel Vanotegem's code linked above, I discovered that I get an authentication error calling the LogonUser function (error code 1326 that gets me a Win32Exception (0x80004005): The user name or password is incorrect).
I tried to use the WNetUseConnection function looking at this and this pages but while I get no error from the function (after substituting it in the Michiel code), when I try to move the file I get the same UnauthorizedAccessException: Access to the path is denied.
I also tried to fiddle with the domain passed to the Impersonation Wrapper but I couldn't seem to make it work. I feel like I'm missing something... Can someone kindly point me to the right direction or help me with this issue?
Ty all who contributes in advance.
Edit 15/12/2017 11:52: I discovered that if I try to rerun the LogonUser function immediately after the first error I get a different exception (error 87 Win32Exception (0x80004005): The parameter is incorrect)
I followed on #LennartStoop suggestion, so I enclosed my code in a using block instead of a try finally using the code I borrowed from this answer:
using (NetworkConnection netConn =
new NetworkConnection("\\\\DiskStation", new NetworkCredential("admin", "admin")))
{
// My code here
}
Using this I've been able to establish a connection the network folder and perform all the IO operation I needed so ty very much for the tip Lennart :)

Service won't write to file [duplicate]

This question already has answers here:
How do I debug Windows services in Visual Studio?
(17 answers)
Closed 6 years ago.
I have the following code to write to a log file and it works fine in my console application:
try
{
string log = "some message";
string mFileName = "some directory to the log file";
Console.WriteLine(log);
using (StreamWriter w = File.AppendText(mFileName))
{
w.WriteLine(log);
w.Dispose();
}
}
catch (Exception e)
{
Console.WriteLine("Error Log: " + e.Message);
}
But when I run the code as a service on my PC, it stops logging altogether. I've already checked and the service has same rights as me.
Please note: The service doesn't crash, it simply runs without logging.
Most likely this has something to do with user rights.
My guess is that the system user that starts the service, doesn't have the rights to write to the file location.
One solution is to start the service with the user credentials of your own account (because you have the rights.)
Another solution is to give the user (local system ,service user or IIS user for web-service) write access to the directory, or change the path of the file to a directory were the user has write access.
if you want to make sure, add a try catch block around the using, and write the exception to console, debug or messagebox. Then you will know what goes wrong.
see possible exceptions for File.AppendText on MSDN
My guess is it throws a UnauthorizedAccessException
Why not simply create the StreamWriter directly, wrap it in a try-catch, and if there is an exception, log it with System.Diagnostics.EventLog?
try
{
using (Streamwriter sw = new StreamWriter(path, true)
{
sw.WriteLine(log);
}
}
catch (Exception ex)
{
// Log exception using System.Diagnostics.EventLog
}

Access to the path is Denied When create file by windows service

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

Categories

Resources