├── .github
├── dependabot.yml
└── workflows
│ ├── codeql-analysis.yml
│ └── publish.yml
├── .gitignore
├── .nuget
└── .nuget.config
├── LICENSE
├── NetworkConnection
├── NetworkConnection.cs
├── NetworkConnection.csproj
└── Win32Objects
│ ├── NetResource.cs
│ ├── ResourceDisplaytype.cs
│ ├── ResourceScope.cs
│ └── ResourceType.cs
├── README.md
└── lgtm.yml
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: nuget
4 | directory: "/NetworkConnection"
5 | schedule:
6 | interval: monthly
7 | open-pull-requests-limit: 10
8 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | name: "CodeQL"
2 |
3 | on:
4 | push:
5 | branches: [master, ]
6 | pull_request:
7 | # The branches below must be a subset of the branches above
8 | branches: [master]
9 | schedule:
10 | - cron: '0 15 * * 5'
11 |
12 | jobs:
13 | analyse:
14 | name: Analyse
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - name: Checkout repository
19 | uses: actions/checkout@v2
20 | with:
21 | # We must fetch at least the immediate parents so that if this is
22 | # a pull request then we can checkout the head.
23 | fetch-depth: 2
24 |
25 | # If this run was triggered by a pull request event, then checkout
26 | # the head of the pull request instead of the merge commit.
27 | - run: git checkout HEAD^2
28 | if: ${{ github.event_name == 'pull_request' }}
29 |
30 | # Initializes the CodeQL tools for scanning.
31 | - name: Initialize CodeQL
32 | uses: github/codeql-action/init@v1
33 | # Override language selection by uncommenting this and choosing your languages
34 | # with:
35 | # languages: go, javascript, csharp, python, cpp, java
36 |
37 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
38 | # If this step fails, then you should remove it and run the build manually (see below)
39 | - name: Autobuild
40 | uses: github/codeql-action/autobuild@v1
41 |
42 | # ℹ️ Command-line programs to run using the OS shell.
43 | # 📚 https://git.io/JvXDl
44 |
45 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
46 | # and modify them (or add more) to build your code if your project
47 | # uses a compiled language
48 |
49 | #- run: |
50 | # make bootstrap
51 | # make release
52 |
53 | - name: Perform CodeQL Analysis
54 | uses: github/codeql-action/analyze@v1
55 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish
2 |
3 | on:
4 | push:
5 | branches: master
6 |
7 | jobs:
8 | build:
9 |
10 | runs-on: windows-latest
11 |
12 | steps:
13 | - uses: actions/checkout@v2
14 | - name: Build with dotnet
15 | run: dotnet build NetworkConnection/NetworkConnection.csproj --configuration Release
16 | - name: Pack Nuget
17 | run: dotnet pack NetworkConnection/NetworkConnection.csproj -o . -c Release -p:PackageVersion=1.0.$env:GITHUB_RUN_NUMBER --version-suffix $env:GITHUB_SHA
18 | - name: Publish nuget to Nuget.org
19 | run: dotnet nuget push *.nupkg -k ${{ secrets.NUGET_TOKEN }} -s https://api.nuget.org/v3/index.json
20 | - name: Publish nuget to Github
21 | run: |
22 | sed 's/GITHUB_TOKEN/${{ secrets.GITHUB_TOKEN }}/g' .nuget/.nuget.config > nuget.config
23 | dotnet nuget push "*.nupkg" -s "github"
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/.nuget/.nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Baruch Odem (Rothkoff)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/NetworkConnection/NetworkConnection.cs:
--------------------------------------------------------------------------------
1 | using NetworkConnection.Win32Objects;
2 | using System;
3 | using System.ComponentModel;
4 | using System.Net;
5 | using System.Runtime.InteropServices;
6 |
7 | namespace NetworkConnection
8 | {
9 | ///
10 | /// Represents a network connection along with authentication to a network share.
11 | ///
12 | public class NetworkConnection : IDisposable
13 | {
14 | #region Variables
15 |
16 | ///
17 | /// The full path of the directory.
18 | ///
19 | private readonly string _networkName;
20 |
21 | #endregion
22 |
23 | #region Constructors
24 |
25 | ///
26 | /// Initializes a new instance of the class.
27 | ///
28 | ///
29 | /// The full path of the network share.
30 | ///
31 | ///
32 | /// The credentials to use when connecting to the network share.
33 | ///
34 | public NetworkConnection(string networkName, NetworkCredential credentials)
35 | {
36 | _networkName = networkName;
37 |
38 | var netResource = new NetResource
39 | {
40 | Scope = ResourceScope.GlobalNetwork,
41 | ResourceType = ResourceType.Disk,
42 | DisplayType = ResourceDisplaytype.Share,
43 | RemoteName = networkName.TrimEnd('\\')
44 | };
45 |
46 | var result = WNetAddConnection2(
47 | netResource, credentials.Password, credentials.UserName, 0);
48 |
49 | if (result != 0)
50 | {
51 | throw new Win32Exception(result);
52 | }
53 | }
54 |
55 | #endregion
56 |
57 | #region Events
58 |
59 | ///
60 | /// Occurs when this instance has been disposed.
61 | ///
62 | public event EventHandler Disposed;
63 |
64 | #endregion
65 |
66 | #region Public methods
67 |
68 | ///
69 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
70 | ///
71 | public void Dispose()
72 | {
73 | Dispose(true);
74 | GC.SuppressFinalize(this);
75 | }
76 |
77 | #endregion
78 |
79 | #region Protected methods
80 |
81 | ///
82 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
83 | ///
84 | /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
85 | protected virtual void Dispose(bool disposing)
86 | {
87 | if (disposing)
88 | {
89 | Disposed?.Invoke(this, EventArgs.Empty);
90 | }
91 |
92 | WNetCancelConnection2(_networkName, 0, true);
93 | }
94 |
95 | #endregion
96 |
97 | #region Private static methods
98 |
99 | ///
100 | ///The WNetAddConnection2 function makes a connection to a network resource. The function can redirect a local device to the network resource.
101 | ///
102 | /// A structure that specifies details of the proposed connection, such as information about the network resource, the local device, and the network resource provider.
103 | /// The password to use when connecting to the network resource.
104 | /// The username to use when connecting to the network resource.
105 | /// The flags. See http://msdn.microsoft.com/en-us/library/aa385413%28VS.85%29.aspx for more information.
106 | ///
107 | [DllImport("mpr.dll")]
108 | private static extern int WNetAddConnection2(NetResource netResource,
109 | string password,
110 | string username,
111 | int flags);
112 |
113 | ///
114 | /// The WNetCancelConnection2 function cancels an existing network connection. You can also call the function to remove remembered network connections that are not currently connected.
115 | ///
116 | /// Specifies the name of either the redirected local device or the remote network resource to disconnect from.
117 | /// Connection type. The following values are defined:
118 | /// 0: The system does not update information about the connection. If the connection was marked as persistent in the registry, the system continues to restore the connection at the next logon. If the connection was not marked as persistent, the function ignores the setting of the CONNECT_UPDATE_PROFILE flag.
119 | /// CONNECT_UPDATE_PROFILE: The system updates the user profile with the information that the connection is no longer a persistent one. The system will not restore this connection during subsequent logon operations. (Disconnecting resources using remote names has no effect on persistent connections.)
120 | ///
121 | /// Specifies whether the disconnection should occur if there are open files or jobs on the connection. If this parameter is FALSE, the function fails if there are open files or jobs.
122 | ///
123 | [DllImport("mpr.dll")]
124 | private static extern int WNetCancelConnection2(string name, int flags, bool force);
125 |
126 | #endregion
127 |
128 | ///
129 | /// Finalizes an instance of the class.
130 | /// Allows an to attempt to free resources and perform other cleanup operations before the is reclaimed by garbage collection.
131 | ///
132 | ~NetworkConnection()
133 | {
134 | Dispose(false);
135 | }
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/NetworkConnection/NetworkConnection.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | true
6 | snupkg
7 | true
8 | LICENSE
9 | Represents a network connection along with authentication to a network share
10 | https://github.com/baruchiro/NetworkConnection
11 | https://github.com/baruchiro/NetworkConnection
12 | Git
13 |
14 |
15 |
16 |
17 | True
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/NetworkConnection/Win32Objects/NetResource.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 |
3 | namespace NetworkConnection.Win32Objects
4 | {
5 | ///
6 | /// The net resource.
7 | ///
8 | [StructLayout(LayoutKind.Sequential)]
9 | public class NetResource
10 | {
11 | public ResourceScope Scope;
12 | public ResourceType ResourceType;
13 | public ResourceDisplaytype DisplayType;
14 | public int Usage;
15 | public string LocalName;
16 | public string RemoteName;
17 | public string Comment;
18 | public string Provider;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/NetworkConnection/Win32Objects/ResourceDisplaytype.cs:
--------------------------------------------------------------------------------
1 | namespace NetworkConnection.Win32Objects
2 | {
3 | ///
4 | /// The resource displaytype.
5 | ///
6 | public enum ResourceDisplaytype
7 | {
8 | Generic = 0x0,
9 | Domain = 0x01,
10 | Server = 0x02,
11 | Share = 0x03,
12 | File = 0x04,
13 | Group = 0x05,
14 | Network = 0x06,
15 | Root = 0x07,
16 | Shareadmin = 0x08,
17 | Directory = 0x09,
18 | Tree = 0x0a,
19 | Ndscontainer = 0x0b
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/NetworkConnection/Win32Objects/ResourceScope.cs:
--------------------------------------------------------------------------------
1 | namespace NetworkConnection.Win32Objects
2 | {
3 | ///
4 | /// The resource scope.
5 | ///
6 | public enum ResourceScope
7 | {
8 | Connected = 1,
9 | GlobalNetwork,
10 | Remembered,
11 | Recent,
12 | Context
13 | };
14 | }
15 |
--------------------------------------------------------------------------------
/NetworkConnection/Win32Objects/ResourceType.cs:
--------------------------------------------------------------------------------
1 | namespace NetworkConnection.Win32Objects
2 | {
3 | ///
4 | /// The resource type.
5 | ///
6 | public enum ResourceType
7 | {
8 | Any = 0,
9 | Disk = 1,
10 | Print = 2,
11 | Reserved = 8,
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NetworkConnection
2 |
3 | Represents a network connection along with authentication to a network share.
4 |
5 | 
6 | 
7 | [](https://www.nuget.org/packages/NetworkConnection/)
8 |
9 | Based on [Daniel Hilgarth](https://stackoverflow.com/users/572644/daniel-hilgarth)'s [answer](https://stackoverflow.com/a/5433640/839513) from Stack Overflow.
10 |
11 | ## Usage
12 |
13 | ```cs
14 | using(new NetworkConnection(_directoryPath, new NetworkCredential(_userName, _password)))
15 | {
16 | File.Copy(localPath, _directoryPath);
17 | }
18 | ```
19 |
--------------------------------------------------------------------------------
/lgtm.yml:
--------------------------------------------------------------------------------
1 | extraction:
2 | csharp:
3 | index:
4 | solution: NetworkConnection/NetworkConnection.csproj
--------------------------------------------------------------------------------