Accessing remote files (C#)

mlm

Senior member
Feb 19, 2006
933
0
0
A program I didn't write needs to have access to a remote file. It has all the information it needs: path and the login information to the other computer. However, when it tries to access it, the login information isn't used at all, so the read/write always fails.

If you try to access the computer outside of the program (and logging in) before using the function, everything works fine. I don't want to have to force that on the user though, so I want to make a small function that will effectively do that. Hopefully something that can pretty much stand on its own since I don't want to alter all the code that I'm unfamiliar with.

But I tried the following based off of MS examples and got the error "Invalid Namespace." Does anybody know of any other quick solutions?

ConnectionOptions options = new ConnectionOptions();
options.username = "user";
options.password = "pass";

Management scope = new ManagementScope("\\\\server\\folder", options);

scope.Connect(); // ManagementException ("Invalid Namespace") thrown here
 

Snapster

Diamond Member
Oct 14, 2001
3,916
0
0
A little more detail may be needed to help you. The Management assemblies are used for WMI queries, not really file access. Changing your code: ManagementScope scope = new ManagementScope(@"\\servername\root\CIMV2", options); and you wouldn't get the exception. However I think you need to read up on WMI if you want to go down this route. If you just want file read/write access just use something like a filestream, and impersonate if you need it to be a user other than the one currently logged in and using the application.

using (FileStream fs = new FileStream(@"\\server\folder\file.txt", FileMode.Open))
{
// do stuff
}
 

mlm

Senior member
Feb 19, 2006
933
0
0
How would you specify the alternate user information using a FileStream?
 

imported_Dhaval00

Senior member
Jul 23, 2004
573
0
0
We run WMI scripts internally, and I don't know how that would factor out in your environment, but have you set the options.Authority property to "
ntdlmdomain : DOMAIN
"; in your C# code (replace DOMAIN with THE REMOTE PC's domain)? The snippet you pasted originally seems to miss out on this step...

PS: the quoted text would get transformed to smileys... there are no spaces before and after the colon.
 

BradAtWork

Senior member
Sep 5, 2005
320
0
0
Are you on a domain? Is the machine you're trying to connect on a domain, even a different one? And you just need different domain credials to access the machine?

If so you can use LogonUser.

If not, and you're using a local user account on the remote machine you cant.

If thats the case use the WNetAddConnection2 api. Its the equivilant of doing a Net Use \\remoteMachine

but saves you going to the command line to do it.

Then use WNetCancelConnection2 to disconnect.

Not sure of a better way to do it.

Sorry if I read your post wrong and this is useless.