Reading hidden share in C#
Asked Answered
K

3

7

So I have a small C# app that needs to periodically check the contents of directories on multiple machines on the network. I thought I could just read \hostname\C$ as a directory path, but with the normal Directory class there doesn't seem to be a way to authenticate against the other servers so you can access the hidden share. I'm sure there's an easy way to do this that I've overlooked, but at the moment I'm a bit stumpted.

Keown answered 26/9, 2008 at 15:9 Comment(1)
This should work. What is the exception you are getting?Bespectacled
B
6

From http://bytes.com/forum/thread689145.html:

All processes run in the context of a logged-in user account. If you want to open a file on another computer, your application must be running in the context of a user that has permissions to open files on that machine. You can do this with Impersonation.

The easiest way seems to be to give the current user appropriate rights on the other machines.

Briarwood answered 26/9, 2008 at 15:13 Comment(1)
This is the best approach as well, as it will eliminate the need to deal with authentication in your software (which is easy to get wrong).Brocade
D
2

To authenticate with a share to which the user running the process does not have permission (which is often the case for administrative shares), try running the net use command:

net use SERVERNAME\IPC$ /user:USERNAME PASSWORD

Try running this in a separate process before the code which actually tries to access the share, e.g.:

ProcessStartInfo psi = new ProcessStartInfo(
    "net", "use " + SERVERNAME + @"\IPC$ /user:" + USERNAME + " " + PASSWORD);
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
p.Close();
// The code to access the share follows...

This is useful if it is not appropriate to give permission to the share for the user account running the process, e.g. for a security model where an end-user application needs to access data on a share to which the user herself should not have direct access.

Does answered 26/9, 2008 at 15:43 Comment(0)
P
0

Are you looking for a way to set the current user at run-time?

If not, as long as the user running the process has access to those machines, this will work for you:

DirectoryInfo di = new DirectoryInfo(@"\\machineName\c$\temp");

FileInfo[] files = di.GetFiles();

foreach (FileInfo f in files)
{
    Debug.WriteLine(f.Name);
}
Paris answered 26/9, 2008 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.