c# 윈도우 공유폴더 접근

C# 2020. 10. 15. 12:46
반응형

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;

 

 

 

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

 

c#을 이용하여 공유폴더 접근하는 방법

 

[원문] http://www.nullskull.com/q/10116970/accessing-shared-folder-on-a-network-using-c-code.asp

반응형
블로그 이미지

visualp

c#, java

,