Strange behaviour from System.IO.DirectoryInfo. Exists function - c#

I am developing an application using c# and asp. It need to access some places in the local network . There is a text box in the form which accept the path to be accessed from the user and will store it to a string variable named location.
The if loop always return false if the application run in windows 7. and it occurs only when I run from the installed application, otherwise it will return true if the path is true. Here is the code:
The input to textbox BackupLocation is like this
\\192.168.0.33\Others (F)
. It work fine if the application is hosted on a system which have windows XP
System.IO.DirectoryInfo locationInfo = new System.IO.DirectoryInfo(BackupLocationTxt.Text);
if (locationInfo.Exists) // always return false if the application run in windows 7
{
}
Why this happens ?

This happens because the user you are running your application under doesn't have authorization to read those folders. You might need to grant read access to those folders to the account you are running your site under.

Try System.IO.Directory.Exists(string path) instead.

Your ASP.NET application doesn't have permissions to the folder on other computer in local network.
Try use windows service started under LocalService account.

Related

Windows Service getting access denied exception while writing to Network Drive

I have an interactive windows service which run on a Local System account and with Interact with desktop checkbox checked(this is mandatory for my project as my service needs to invoke .exe with UI ). I am getting an exception as Access denied while writing to network drive. I am passing the UNC path from config file. i tried giving full control access to anonymous user on the folder which i want to access but its still not working. i cannot run my windows service under Network service account or under any other account as suggested in some other posts because i want it interact with desktop check box checked. is there any way to achieve this?
Edit: UNC path of network drive: //server/ABC/pqr
my service should create .txt file in pqr folder. should have access to delete it afterwords too.
i have tried creating anonymous user for pqr folder and giving it full control but still i am getting access denied exception. as i mentioned before i cannot run it under any other account other than local system account because it will automatically disable interact with desktop option in the properties of that service. is there any way to make it run under Network Service Account and still keep it interactive(interact with desktop option checked in the properties of service)?
Try using the following nugget package named SimpleImpersonation
This way you could wrap the code you use to access your remote file location like this:
using (Impersonation.LogonUser(domain, username, password, logonType))
{
// do whatever you want as this user.
}
It worked for me. I used it to turn on and turn off a windows service remotely. Like this:
await Task.Factory.StartNew(() =>
{
using (
Impersonation.LogonUser(serviceInfo.Domain, serviceInfo.User, serviceInfo.Pswd,
Environment.MachineName.Equals(serviceInfo.ComputerName,
StringComparison.InvariantCultureIgnoreCase)
? LogonType.Network
: LogonType.Interactive))
{
var service = new ServiceController(serviceInfo.ServiceName, serviceInfo.ComputerName);
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(60));
}
else
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(60));
}
}
});
(the snippet was taken from the project site)

Creating a new directory in a Windows 10 Universal App UWP

I am attempting to create a directory using this method that fires after a button press in app, as well as add a file to it:
DirectoryInfo d = new DirectoryInfo(#"..\\newFolder\\");
FileInfo f = new FileInfo(#"..\\newFolder\\foo.txt");
if (!d.Exists)
{
d.Create();
}
if (!f.Exists)
{
f.Create().Dispose();
}
Here's the error that is producded in my Universal App as a result of doing this:
An exception of type 'System.UnauthorizedAccessException'
occurred in System.IO.FileSystem.dll but was not handled in user code
Additional information: Access to the path
'C:\Users\[username]\Documents\MyApp\bin\x86\Debug\AppX\newFolder' is denied.
Any one familiar with this error or know of any suggestions?
EDIT
In addition to the below, this is a Great resource for working with file systems in the Windows 10 Universal App environment: File access and permissions (Windows Runtime apps) https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh758325.aspx
The problem is that you are trying to create a file inside your app's install folder, and that is not allowed for Universal Apps. You can only create folders inside your local data folder.
Try this:
using Windows.Storage;
var localRoot = ApplicationData.Current.LocalFolder.Path;
DirectoryInfo d = new DirectoryInfo(localRoot + "\\test");
if (!d.Exists)
d.Create();
Try This
public static async void WriteTrace()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
}
Every application runs under (by) a specific user and inherit it's privileges, authorities, limitations and ...
so
The User that your app runs under it, haven't enough privilege and can't create a folder
SO you can:
Use Impersonation (search impersonation c#) and code your app to runs as another User with required privilege (Like Administrator). after that your application always runs as administrator (or specific user) automatically. (If you impersonation your app as Administrator, Be aware of Security issues)
Run your application as Administrator (or a user with enough privilege) manually. (for Administrator right click on your-app.exe and click on "Run as ...")
Change security settings and access limits for your working directories (e.g C:\Users[username]\Documents\MyApp\bin\x86\Debug\AppX\newFolder ) and give write access to your username
Run your application with Administrative privileges and it should be done.

Accessing Network Path in Windows Service C#

I have developed a windows service using local system as Account. I have used
network path of file
FileInfo fi = new FileInfo(#"\\epm-server\penDocuments_LabMeds\" + Convert.ToString(dr["mrn"]) + "\\SyncedXML\\" + Convert.ToString(dr["xmlfile"]));
if (!fi.Exists)
boolFileNotFound = true;
A dynamic path of a file that is built from database.
It works fine when I run Windows Service in Debug Mode, but when I install it then fileNotExists returns TRUE always like the file doesnt exist but infact it does exist.
This is bugging me a lot now. Kindly help me why its not working. Its a server path. Its getting opened in my PC.
Thanks
Did you notice the double backslashes in front and after SyncedXML (\\SyncedXML\\)?
This is probably the cause of your error.
Additionally I'd use string.Format in such cases to reduce the inadvertently addition of unwanted characters:
var path = string.Format(#"\\epm-server\penDocuments_LabMeds\{0}\SyncedXML\{1}", dr[mrn], dr[xmlfile]);
var fi = new FileInfo(path);
Edit:
If it's permission-related, then it's very likely that your local system account (in whose context the service is running) isn't allowed to access the epm-server.
The path is accessible if you're opening it directly or if you're running the service in debug mode as this is happening in your user context (e.g. YOURDOMAIN\vickyshazad), and you're allowed to access the ressource, whereas NT AUTHORITY\SYSTEM is not.
It's usually a good practise to have a special service account for your developed windows service and grant this user only and exactly the required permissions (least privilege). Maybe ask your system administrator for a service user.
Local System (NT AUTHORITY\SYSTEM) is a highly privileged account that's not recommended to use in general (see MSDN).
Most services do not need such a high privilege level. If your service does not need these privileges, and it is not an interactive service, consider using the LocalService account or the NetworkService account.

Not all info about process in Process.GetProcesses when run in service by Local Service account

I have this code:
[PermissionSet(SecurityAction.Assert, Name = "FullTrust")]
public List<WinInfo> GetWindows()
{
try
{
var isFullTrust = Assembly.GetExecutingAssembly().IsFullyTrusted;
if (isFullTrust)
{
return Process.GetProcesses().Where(z => !string.IsNullOrEmpty(z.MainWindowTitle))
.Select(z => new WinInfo
{
ProcessID = z.Id,
ProcessName = z.ProcessName,
WinID = z.MainWindowHandle,
WindowTitle = z.MainWindowTitle
}).ToList();
}
else
return null;
}
catch (Exception ex)
{
Trace.Write(ex.Message);
return null;
}
}
When I test in on my local computer under my current user (with admin rights) it works ok, displaying all the processes, that have windows. But when I call this code from a windows service, run under "Local Service" account, then the list is empty. I attached to the process, and through debug I found that "Process.GetProcesses()" returns all the processes, but all of them have MainWindowHandle as 0 and MainWindowTitle as empty, even when they do have windows. So what is wrong with my code?
Edit I edited code, so that it checks the assembly for full trust and have PemmissionSet that should grant the code the neccessary rights. Still the result is the same. When I debug, I can see, that "isFullTrust" is "True" and code executes with no exceptions. Still the list is empty, because none of the processes contains not-empty MainWindowTitle
According to this thread :
The problem you're seeing is because by default service don't have access to any interactive desktops. I don't recommend interacting with the desktop from a service (#1, there may not be any desktop, #2 there may be multiple desktops, #3 interacting with the desktop from service in Vista is not implemented) but, you can check the "Interace with desktop" in your services properties.
maybe you can try to create an hidden form?
Surely you need to run that under the user account! Why would applications with open windows be running under the local system account? That's for windows services etc
It could also be related to your process requiring full trust
From MSDN: The Process class has a LinkDemand and an
InheritenceDemand for FullTrust on it. This means that if your
assembly is not fully trusted, it will be unable to kick off new
Processes or get information about running processes
Maybe this is a question of priviliges.
According to this link LocalService has minimum privileges on the local computer.
you should use Local system Account

a required privilege is not held by the client while uploading a temporary registry (C#)

While I am trying to upload a registry in my registries using the C# code , the application is throwing the error "a required privilege is not held by the client". If I am using the same code on some other machine it is working fine but not particularly on my machine
I am using below mentioned code to upload the registry files
Process my_p = new Process();
my_p.StartInfo.FileName = "reg";
my_p.StartInfo.Arguments = "load HKLM\TEST C:\Documents and Settings\Administrator\NTUSER.DAT";
my_p.Start();
my_p.WaitForExit();
System.IO.StreamReader srOutPut = my_p.StandardOutput;
System.IO.StreamReader srError = my_p.StandardError;
my_p.Close();
results = srOutPut.ReadToEnd().Trim();
Errors = srError.ReadToEnd().Trim();
Moreover One thing I have noticed that the above code I am using in http based web site, but when I am using it in a File Syatem based web site it is working fine. Please help I am not getting the error.
Regards,
Vikram
You can load RegLoadKey function directly to load the hive as a subkey. Another API is RegLoadAppKey but it works only starting from Windows Vista. Different versions of Reg.exe use the API. How you can read in the description the RegLoadKey you need have SE_RESTORE_NAME and SE_BACKUP_NAME privileges and enable these (see http://msdn.microsoft.com/en-us/library/ms717797.aspx). If you are in the Group of Administrators or Backup Operators you have these privileges. One more problem can be if Reg.exe use RegLoadKey function and you have a local administrative rights, but you start on Vista or Windows 7 a command without admin rights because of UAC (User Account Control).

Categories

Resources