使用 C# System.Net.NetworkCredential 访问共享文件夹

本文将介绍如何使用 C# 中的 System.Net.NetworkCredential 类访问远程共享文件夹,并提供详细的代码示例和解释,帮助您轻松实现文件访问操作。

准备工作

在开始之前,您需要确保以下几点:

  1. 您的本地计算机上已经设置了共享文件夹。
  2. 您已经为该共享文件夹设置了适当的权限,并获得了访问权限的用户名和密码。

代码示例

以下代码示例展示了如何使用 System.Net.NetworkCredential 访问共享文件夹:

using System;
using System.IO;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        string shareFolder = @'\server\share';
        string userName = 'user';
        string password = 'password';
        NetworkCredential credentials = new NetworkCredential(userName, password);

        using (new NetworkConnection(shareFolder, credentials))
        {
            // Access the shared folder here
            string[] files = Directory.GetFiles(shareFolder);
            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }
    }
}

public class NetworkConnection : IDisposable
{
    private readonly string _networkName;

    public NetworkConnection(string networkName, NetworkCredential credentials)
    {
        _networkName = networkName;

        var netResource = new NetResource
        {
            Scope = ResourceScope.GlobalNetwork,
            ResourceType = ResourceType.Disk,
            DisplayType = ResourceDisplayType.Share,
            RemoteName = networkName
        };

        var result = WNetAddConnection2(
            netResource,
            credentials.Password,
            $'{credentials.Domain}\{credentials.UserName}',
            0);

        if (result != 0)
        {
            throw new IOException('Error connecting to remote share', result);
        }
    }

    ~NetworkConnection()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        WNetCancelConnection2(_networkName, 0, true);
    }

    [DllImport('mpr.dll')]
    private static extern int WNetAddConnection2(NetResource netResource,
        string password, string username, int flags);

    [DllImport('mpr.dll')]
    private static extern int WNetCancelConnection2(string name, int flags,
        bool force);
}

[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
    public ResourceScope Scope;
    public ResourceType ResourceType;
    public ResourceDisplayType DisplayType;
    public int Usage;
    public string LocalName;
    public string RemoteName;
    public string Comment;
    public string Provider;
}

public enum ResourceScope : int
{
    Connected = 1,
    GlobalNetwork,
    Remembered,
    Recent,
    Context
}

public enum ResourceType : int
{
    Any = 0,
    Disk = 1,
    Print = 2,
    Reserved = 8,
}

public enum ResourceDisplayType : int
{
    Generic = 0x0,
    Domain = 0x01,
    Server = 0x02,
    Share = 0x03,
    File = 0x04,
    Group = 0x05,
    Network = 0x06,
    Root = 0x07,
    ShareAdmin = 0x08,
    Directory = 0x09,
    Tree = 0x0a,
    NdsContainer = 0x0b
}

代码解释

  1. 定义变量:首先定义了要访问的共享文件夹路径 shareFolder、用户名 userName 和密码 password,并使用这些信息创建了一个 System.Net.NetworkCredential 对象 credentials

  2. 创建 NetworkConnection:该类使用 WNetAddConnection2 函数连接到远程共享,并在 Dispose 方法中使用 WNetCancelConnection2 函数断开连接。

    • WNetAddConnection2 函数用于建立网络连接,参数分别为网络资源、密码、用户名和标志。
    • WNetCancelConnection2 函数用于断开网络连接,参数分别为网络资源、标志和是否强制断开。
  3. 使用 using 语句:通过 using 语句创建 NetworkConnection 对象,在 using 块中可以执行任何与共享文件夹相关的操作。当 using 块结束时,NetworkConnection 对象将自动被释放,从而断开与共享文件夹的连接。

总结

通过以上代码示例和解释,您可以轻松地使用 C# 中的 System.Net.NetworkCredential 类访问远程共享文件夹,实现文件访问和操作。

注意:该代码示例需要引用 System.Runtime.InteropServices 命名空间。

安全提示:请务必注意安全问题,不要将用户名和密码直接硬编码在代码中,建议使用安全的方法存储和管理凭据。

使用 C# System.Net.NetworkCredential 访问共享文件夹

原文地址: https://www.cveoy.top/t/topic/oUjX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录