Posted
Filed under C#
I found this solution to work for me when trying to access a file share on another computer.  It basically simulates doing a NET USE command where you can specify the credentials to use on the remote end.  The nice part is that you do not have to impersonate the user and it works across domains and workgroup computers.

First, declare these functions and types in your class.

using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel;

public class YourClass {
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2A(ref NetResource pstNetRes, string psPassword, string psUsername, int piFlags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2A(string psName, int piFlags, int pfForce);

[StructLayout(LayoutKind.Sequential)]
private struct NetResource {
    public int iScope;
    public int iType;
    public int iDisplayType;
    public int iUsage;
    public string sLocalName;
    public string sRemoteName;
    public string sComment;
    public string sProvider;
}

private const int RESOURCETYPE_DISK = 0x1;

Then, add these two methods.
   
    private void LoginToShare(string serverName, string shareName, string user, string password) {
        string destinationDirectory = string.Format(@"\\{0}\{1}", serverName, shareName);

        NetResource nr = new NetResource();
        nr.iScope = 2;
        nr.iType = RESOURCETYPE_DISK;
        nr.iDisplayType = 3;
        nr.iUsage = 1;
        nr.sRemoteName = destinationDirectory;
        nr.sLocalName = null;

        int flags = 0;
        int rc = WNetAddConnection2A(ref nr, password, user, flags);

        if (rc != 0) throw new Win32Exception(rc);
    }

    private void LogoutFromShare(string serverName, string shareName) {
        string destinationDirectory = string.Format(@"\\{0}\{1}", serverName, shareName);
        int flags = 0;
        int rc = WNetCancelConnection2A(destinationDirectory, flags, Convert.ToInt32(false));
    }


In your code, call the LoginToShare with the server, share, user, and password needed.  Then simply use the standard \\server\share\path conventions for accessing files on remote computers.  Call the LogoutFromShare when you're done.

http://www.nullskull.com/q/10116970/accessing-shared-folder-on-a-network-using-c-code.aspx

2016/01/26 10:05 2016/01/26 10:05