简体   繁体   English

在C#中读取隐藏的份额

[英]Reading hidden share in C#

So I have a small C# app that needs to periodically check the contents of directories on multiple machines on the network. 所以我有一个小的C#应用​​程序需要定期检查网络上多台机器上的目录内容。 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. 我以为我只能读取\\ hostname \\ C $作为目录路径,但是使用普通的Directory类似乎没有办法对其他服务器进行身份验证,因此您可以访问隐藏的共享。 I'm sure there's an easy way to do this that I've overlooked, but at the moment I'm a bit stumpted. 我确信有一个简单的方法可以做到这一点,我忽略了,但此刻我有点难过。

From http://bytes.com/forum/thread689145.html : 来自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. 最简单的方法似乎是为当前用户提供其他计算机上的适当权限。

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命令:

net use SERVERNAME\IPC$ /user:USERNAME PASSWORD

Try running this in a separate process before the code which actually tries to access the share, eg: 尝试在实际尝试访问共享的代码之前在单独的进程中运行它,例如:

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, eg 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. 如果不适合为运行该进程的用户帐户授予共享权限,这是非常有用的,例如,对于最终用户应用程序需要访问用户本身不应该直接访问的共享上的数据的安全模型。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM