[C# 문법] C# 공유폴더(Network Drive) 접근하기


안녕하세요.

 

오늘은 C# 에서 공유폴더 (Network Drive) 에 접근하는 방법에 대해서 알려드리려고 합니다.

 

최근에 프로젝트를 하면서 공유폴더 관리 프로그램을 만들었기 때문에, 지식을 같이 공유 하고자 포스팅 하게 되었습니다.

 

그럼 바로, 예제 프로그램을 통해서 어떻게 C# 문법으로 공유폴더에 접근하는지 알려 드리겠습니다.


 

먼저, 아래와 같이 빈 윈폼 프로젝트를 생성해 주시기 바랍니다.

 

빈 윈폼 프로젝트 생성



이제 네트워크 드라이브에 접근하는 소스코드를 작성해 보도록 하겠습니다.


먼저 네트워크 드라이브에 접근할 NetworkConnector 클래스를 하나 추가해서 만들어 주시기 바랍니다.


NetworkConnector.cs


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.InteropServices;

using System.Text;

using System.Threading.Tasks;

 

namespace Test

{

    public class NetworkConnector

    {

        public NETRESOURCE NetResource = new NETRESOURCE();

 

        [DllImport("mpr.dll", CharSet = CharSet.Auto)]

        public static extern int WNetUseConnection(

                    IntPtr hwndOwner,

                    [MarshalAs(UnmanagedType.Struct)] ref NETRESOURCE lpNetResource,

                    string lpPassword,

                    string lpUserID,

                    uint dwFlags,

                    StringBuilder lpAccessName,

                    ref int lpBufferSize,

                    out uint lpResult);

 

        [DllImport("mpr.dll", EntryPoint = "WNetCancelConnection2", CharSet = CharSet.Auto)]

        public static extern int WNetCancelConnection2A(String lpName, int dwFlags, int fForce);

 

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

        public struct NETRESOURCE

        {

            public uint dwScope;

            public uint dwType;

            public uint dwDisplayType;

            public uint dwUsage;

            public string lpLocalName;

            public string lpRemoteName;

            public string lpComment;

            public string lpProvider;

        }

 

        public int TryConnectNetwork(string remotePath, string userID, string pwd)

        {

            int capacity = 1028;

            uint resultFlags = 0;

            uint flags = 0;

            StringBuilder sb = new StringBuilder(capacity);

 

            NetResource.dwType = 1// 공유 디스크

            NetResource.lpLocalName = null;   // 로컬 드라이브 지정하지 않음

            NetResource.lpRemoteName = remotePath;

            NetResource.lpProvider = null;

 

            int result = WNetUseConnection(IntPtr.Zero, ref NetResource, pwd, 

                userID, flags, sb, ref capacity, out resultFlags);

 

            return result;

        }

 

        public void DisconnectNetwork()

        {

            WNetCancelConnection2A(NetResource.lpRemoteName, 10);

        }

    }

}

 

Colored by Color Scripter

cs

 

이제는 MainForm.cs 소스코드를 작성해 보도록 하겠습니다.


MainForm.cs


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace Test

{

    public partial class Form1 : Form

    {

        //공유폴더 접근 객체 생성

        NetworkConnector share1 = new NetworkConnector(); 

 

        public Form1()

        {

            InitializeComponent();

 

            this.Load += TestForm_Load;

        }

 

        public void TestForm_Load(object sender, EventArgs e)

        {

            ConnectNetworkDrive(); //네트워크 드라이브 접근

        }

 

        public void ConnectNetworkDrive()

        {

            string ip = @"\\127.0.0.1\beombeomjojo"//네트워크 드라이브 주소

            string userID = @"administrator";            // 사용자 계정

            string pwd = "123456";             // 비밀번호

 

 

            while (true)

            {

                int state = share1.TryConnectNetwork(ip, userID, pwd);

 

                if (TryConnectResult(state) == true)

                {

                    MessageBox.Show(string.Format("Shart folder Connected. {0}", ip));

                    break;

                }

            }

        }

 

        /// <summary>

        /// 연결 상태 정보 반환 메서드

        /// </summary>

        /// <param name="state"></param>

        /// <returns></returns>

        private bool TryConnectResult(int state)

        {

            bool result = true;

 

            if (state == 0)

            {

                result = true;

            }

            else

            {

                result = false;

 

                switch (state)

                {

                    case ERROR_CODE.NO_ERROR:

                        break;

                    case ERROR_CODE.ERROR_ACCESS_DENIED:

 

                        break;

                    case ERROR_CODE.ERROR_ALREADY_ASSIGNED:

                        break;

                    case ERROR_CODE.ERROR_BAD_DEV_TYPE:

                        break;

                    case ERROR_CODE.ERROR_BAD_DEVICE:

                        break;

                    case ERROR_CODE.ERROR_BAD_NET_NAME:

                        break;

                    case ERROR_CODE.ERROR_BAD_PROFILE:

                        break;

                    case ERROR_CODE.ERROR_BAD_PROVIDER:

                        break;

                    case ERROR_CODE.ERROR_MULTIPLE_CONNECTION:

                    case ERROR_CODE.ERROR_BAD_USER_OR_PASSWORD:

                        break;

                    case ERROR_CODE.ERROR_BUSY:

                        break;

                    case ERROR_CODE.ERROR_CANCELLED:

                        break;

                    case ERROR_CODE.ERROR_CANNOT_OPEN_PROFILE:

                        break;

                    case ERROR_CODE.ERROR_DEVICE_ALREADY_REMEMBERED:

                        break;

                    case ERROR_CODE.ERROR_EXTENDED_ERROR:

                        break;

                    case ERROR_CODE.ERROR_INVALID_ADDRESS:

                        break;

                    case ERROR_CODE.ERROR_INVALID_PARAMETER:

                        break;

                    case ERROR_CODE.ERROR_INVALID_PASSWORD:

                        break;

                    case ERROR_CODE.ERROR_NETWORK_BUSY:

                        break;

                    case ERROR_CODE.ERROR_NO_NET_OR_BAD_PATH:

                        break;

                    case ERROR_CODE.ERROR_NO_NET_OR_BAD_SERVER:

                        break;

                    case ERROR_CODE.ERROR_UNEXP_NET_ERR:

                        break;

                    default:

                        break;

                }

            }

 

            return result;

        }

    }

 

    /// <summary>

    /// 네트워크 드라이브 에러코드 Class

    /// </summary>

    public class ERROR_CODE

    {

        public const int NO_ERROR = 0;

        public const int ERROR_NO_NET_OR_BAD_SERVER = 53;

        public const int ERROR_BAD_USER_OR_PASSWORD = 1326;

        public const int ERROR_ACCESS_DENIED = 5;

        public const int ERROR_ALREADY_ASSIGNED = 85;

        public const int ERROR_BAD_DEV_TYPE = 66;

        public const int ERROR_BAD_DEVICE = 1200;

        public const int ERROR_BAD_NET_NAME = 67;

        public const int ERROR_BAD_PROFILE = 1206;

        public const int ERROR_BAD_PROVIDER = 1204;

        public const int ERROR_BUSY = 170;

        public const int ERROR_CANCELLED = 1223;

        public const int ERROR_CANNOT_OPEN_PROFILE = 1205;

        public const int ERROR_DEVICE_ALREADY_REMEMBERED = 1202;

        public const int ERROR_EXTENDED_ERROR = 1208;

        public const int ERROR_INVALID_PASSWORD = 86;

        public const int ERROR_NO_NET_OR_BAD_PATH = 1203;

        public const int ERROR_INVALID_ADDRESS = 487;

        public const int ERROR_NETWORK_BUSY = 54;

        public const int ERROR_UNEXP_NET_ERR = 59;

        public const int ERROR_INVALID_PARAMETER = 87;

        public const int ERROR_MULTIPLE_CONNECTION = 1219;

    }

}

 

Colored by Color Scripter

cs

 

여기까지 소스코드를 작성하였다면, 이제 프로그램을 실행해 보도록 할게요.

 

저는 테스트로 제 개인 컴퓨터에 네트워크 드라이브를 하나 만들었어요!

 


위에서 BeomBeomJoJo 라고 해서 네트워크 드라이브를 하나 만들었습니다.

이제 프로그램을 실행해서 제대로 접근하는지 확인해 보도록 하겠습니다.


실행 결과



위와 같이 제대로 접근이 된 것을 확인할 수 있습니다.


감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY