Remote Shared folders and drives C# - c#

I want to access drives/folders/sub-folders/files on remote machines over network for a machine in C#.
I know of a using WMI for this. However WMI might not be executable over remote machines due to security permissions.
What are alternative way in C# to enumerate the folders/subfolders/files for remote machines over the network.
Thanks!
Gagan

Shared folders on a UNC path can be enumerated just like local directories, using the classes in the System.IO namespace, like Directory.EnumerateFiles.
foreach (var file in Directory.EnumerateFiles(#"\\machine\c$"))
{
}
However, as you say, there's a question of credentials. If you need to specify different credentials to access the shares, you'll have to authenticate against the remote machine. Luckily, there's a great solution in this answer for creating ad-hoc network connections:
using (new NetworkConnection("\\machine\c$", new NetworkCredential("username", "password")))
{
foreach (var file in Directory.EnumerateFiles(#"\\machine\c$"))
{
}
}

You can use forfiles, i am assuming all the machines are Windows.
Refer to this link for more information: Forfiles

Related

Access to the path is denied in ASP.Net

I have an ASP.Net application running in IIS which creates a file in a specified location using CsvWriter. If I use the full UNC path I get error that Access to the path is denied, however if I use Drive letter it works fine. What is puzzling me is that it does work with UNC path in development environment.
This code which creates the file
using (var writer = new StreamWriter(fileName))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteField("Foo");
csv.WriteField("Bar");
csv.NextRecord();
}
Following advice various posts such as Access to the path is denied and IIS7 Permissions Overview - ApplicationPoolIdentity and MS Documentation: Application Pool Identities. I was initially convinced my problem was security related. This was supported by the fact that the application would run perfectly in development environment (IIS Express) which uses my user credentials but not under IIS which uses Application Pool Identity. I gave MyApplicationPoolIdentity full access to the specific directory to no avail.
However, I discovered that if I use the drive letter (C:\myDirectory\mySubDirectory\myFile.csv) as opposed to the UNC path (\\myServer\myDirectory\mySubDirectory\myFile.csv) in production the file is created perfectly. Even though I have the application working my concern is that I may have some configuration issue with IIS or my server which may bite me later. So my question is what would cause the create file/write to fail using UNC path and not using Drive letter?
I am using Windows Server 2016.
Thanks
Tony
I think it is caused by permission issues. First, did you get any related error messages? Or you can try the following methods:
1.you can use Process Monitor to see which account is being used to access the share and what permission are required.
2.Check to ensure the account that IIS is running under has needed rights to the troublesome UNC.

C# Impersonation technique

I wanted to remove a config file from a remote machine having IP as : sj1slm612. Now the problem is i do not have full modification rights to that remote machine, so I'm using impersonation technique to do this. Normally when I'm connected to this remote machine via putty, I use 'sudo'. So my question is will the following code be able to solve my problem ? Thanks.
My Code :
AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
using (WindowsIdentity Authorized_user = new WindowsIdentity("sj1slm612\\wtsnqa", "password"))
{
using (WindowsImpersonationContext context = Authorized_user.Impersonate())
{
File.Delete(#"/apps/instances/express_13000/configuration/standalone-full.xml");
File.Delete(#"/apps/instances/query_13100/configuration/standalone-full.xml");
File.Delete(#"/apps/instances/wppapi_13200/configuration/standalone-full.xml");
File.Delete(#"/apps/instances/wppgui_13300/configuration/standalone-full.xml");
Console.WriteLine("All config files removed from sj1slm612");
Console.ReadLine();
There are 2 problems with your approach:
You are trying to impersonate a remote machine account on a local machine; this won't work. The credentials of a machine account can only be validated by that machine. In addition, that account has no rights on the local machine, so it doesn't really make sense to impersonate it. You need to impersonate a domain account. When you use a tool like putty, the credentials are sent to the remote machine and not validated by the local machine. This is why you can use a machine account of the remote machine.
You need to give proper paths for the files. Nowhere do you indicate that these files are on the remote machine. Use something like "\\machine\c$\path\to\file".
The details on what are going to work or not will depend on your network and OS, which you didn't specify, though it sounds Linux-ish. There may be a different syntax for referring to remote files that you need to use.

Network Share/SMB Client

I'm trying to read a file from a android phone to a Windows share. I'm using now the StreamWriter, like below:
StreamWriter outfile = new StreamWriter(#"\\10.16.68.253\sam\AllTxtFiles.txt");
outfile.WriteLine("TESTGENREOIADNIWAN");
But i get a Access Denied. I already added the permission to the manifest. And i tested the share using the ES File Explorer (with everyone access). I used the same lines of code on a WPF app and works fine, so my problem is in Android app.
I already tried to change the connection string like the ES, smb://10.16.68.253/sam/AllTxtFiles.txt, but no luck.
Anyone accomplished this ?
Tks !
for me I had to set up the string like this "smb://username:password#local ip/" for the root of my server's Windows share.
You have to make sure the connection to the SMB share is authenticated before trying to access any files. You have to use API calls to do this, because this stuff is done in the Win32 layer outside of managed code.
Here's a start:
http://www.pinvoke.net/default.aspx/mpr/WNetAddConnection.html
Are you sure you are able to read/write files using ESFileExplorer with EVERYONE ACCESS permissions?
Windows is a very secured OS. You need to grant permissions to a particular profile.
Example:
Create a new profile name on windows.
Give that new profile name a password. (must have a password to share something)
Give the folder or files permission to share access to that profile with password.
Access the folder or files using smb along with the profile username and password. Such as
"smb://username:password#local ip"
StreamWriter outfile = new StreamWriter(smb:\\username:password#"\\10.16.68.253\sam\AllTxtFiles.txt");
outfile.WriteLine("TESTGENREOIADNIWAN");

Streamwriter issue with remote machine

I am trying to create a file on the remote machine but I am getting The "Network name cannot be found". I checked the network path and I was able to access the path from my machine. Could you please let me know what could be wrong?
Here is my code.
using (StreamWriter sw = new StreamWriter("\\\\servername\\TEST1\\TEST\\NEWFILE.csv", true))
{
sw.WriteLine(sw);
}
Go to \servername\TEST1 and give write permission to the user or aspnet (if you have a web application) on test folder and then re-run your program. It will work.
To give write permissions, just refer to this article:
How to share a folder/File
In case it still does not work, replace servername with server IP address and do the same as stated above.
Give the access rights to the user under which this application runs either it is a IIS pool or windows service etc
it is surely a security isssue. you need to give Write access to the remote machine

Reading UNC path with FileSystemWatcher [duplicate]

I am trying to run a file watcher over some server path using windows service.
I am using my windows login credential to run the service, and am able to access this "someServerPath" from my login.
But when I do that from the FileSystemWatcher it throws:
The directory name \someServerPath is invalid" exception.
var fileWatcher = new FileSystemWatcher(GetServerPath())
{
NotifyFilter=(NotifyFilters.LastWrite|NotifyFilters.FileName),
EnableRaisingEvents=true,
IncludeSubdirectories=true
};
public static string GetServerPath()
{
return string.Format(#"\\{0}", FileServer1);
}
Can anyone please help me with this?
I have projects using the FileSystemWatcher object monitoring UNC paths without any issues.
My guess from looking at your code example may be that you are pointing the watcher at the root share of the server (//servername/) which may not be a valid file system share? I know it returns things like printers, scheduled tasks, etc. in windows explorer.
Try pointing the watcher to a share beneath the root - something like //servername/c$/ would be a good test example if you have remote administrative rights on the server.
With regards to the updated question, I agree that you probably need to specify a valid share, rather than just the remote server name.
[Update] Fixed previous question about the exception with this:
specify the name as #"\\someServerPath"
The \ is being escaped as a single \
When you prefix the string with an # symbol, it doesn't process the escape sequences.
I was just asked this question in regards to FileSystemWatcher code running as a service and the issue is permissions. I searched and found this question and answer but unfortunately none of the answers here solved the problem. Anyway, I just solved it, so I thought I would throw in the solution here for next guy who searches and find this question.
The drive was mapped as a logged in user but the service was running as LocalSystem. LocalSystem is a different account and does not have access to drives mapped by a user.
The fix is to either:
Authenticate first (I use a C# Class to establish a network connection with credentials)
Run your service as a user that has access to the share.
You can test LocalSystem authentication by using a LocalSystem command prompt, see How to open a command prompt running as Local System?
Even though this is already answered I thought I would put in my two cents worth becaus eyou can see this same error even if you supply valid paths.
You will get the same error when the process running the watcher does not have access to the remote share. This will happen if the watcher is in a service running under the System account and the share is created by a user. System does not have access to that share and wont recognize it, you will need to impersonate the user to get access to it.
although you can use a FileWatcher over the network, you will have to account for other factors, like disconnection of the network share. If your connection to the share is terminated (maintenance, lag, equipment reset, etc) you will no longer have a valid handle on the share in your filewatcher
You can't use directory watches over network shares, this is a limitation of the OS, not of .NET.

Categories

Resources