【问题标题】:Connect to share ShareDrive with c#连接以与 c# 共享 ShareDrive
【发布时间】:2018-03-17 20:10:49
【问题描述】:

我想用 c# 连接到共享驱动器。

以下代码仅在启动程序之前在资源管理器中输入路径时才有效(不需要密码)。然后它将工作,直到重新启动worksttion。有谁知道如何避免这种情况?

string _rootDirectory = @"\\mysites.inside-share.xxx.com@SSL\my\xxx\Documents\xxx\";
Directory.CreateDirectory(_rootDirectory);

错误消息:在 mscorlib.dll 中出现“System.IO.IOException”类型的第一次机会异常 mscorlib.dll 中出现“System.IO.IOException”类型的未处理异常 附加信息:未找到网络路径。

环境:PC 试图连接到公司的共享点服务器。该程序正在由用户运行

【问题讨论】:

  • 请指定您的环境。这是在活动目录域还是工作组内?您是在用户下方运行程序还是在后台运行?

标签: c# networking sharepoint share onedrive


【解决方案1】:
/// <summary>
/// Accessing network share folder.
/// </summary>
public class NetUse
{
    string _sharename, _user, _password;

    public NetUse(string ShareFolder,string Username, string  Password)
    {
        _sharename = ShareFolder;
        _user = Username;
        _password = Password;
    }

    [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;

    public void Login()
    {
        string destinationDirectory =  _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);
    }

    public void Logout()
    {
        string destinationDirectory = _sharename;
        int flags = 0;
        int rc = WNetCancelConnection2A(destinationDirectory, flags, Convert.ToInt32(false));
    }
}

用法:

var _NetUse = new NetUse(@"\\mysites.inside-share.xxx.com@SSL\my\xxx\Documents\xxx", "<username>", "<password>");
                    _NetUse.Login();
                    //Do the operations here
                    _NetUse.Logout();

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多