连接到远程共享时出错 - c#

时间:2015-04-21 08:32:31

标签: c# .net .net-4.0

在控制台应用程序中使用.net 4.0

我正在尝试将文件从本地计算机移动到共享驱动器,此代码在using语句中给出了错误。

凭据有效。可能出现什么问题。

namespace UploadList
{
    class Program
    {
      static void Main(string[] args)
        {
           MoveFiles();
        }
      public static void MoveFiles()
        {
            try
            {
                NetworkCredential readCredentials = new 
                NetworkCredential(@"gktrs\PRDSys", "P@ssw0rd123");

                string filepath = "\\\\10.60.90.1\\D$";
                //error at the using statement
                //ERROR : *Error connecting to remote share*
                using (new NetworkConnection(filepath, readCredentials))
                {

                }                    
            }
            catch(Exception ex)
            {

            }
        }
    }
}
public class NetworkConnection : IDisposable
{
    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.UserName,
            0);

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

    ~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 个答案:

答案 0 :(得分:1)

这是我从其他堆栈溢出答案拼凑而成的东西,以解决在MVC中读取共享文件的类似问题。基本上C#dosnt让它变得简单

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;

namespace UnitTestProject2
{
    /// <summary>
    /// MVC 5 dosnt support impersonation via web.config for good reasons microsoft decided one day
    /// </summary>
    internal static class NativeMethods
    {
        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool CloseHandle(IntPtr handle);

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
    }

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }

        protected override bool ReleaseHandle()
        {
            return NativeMethods.CloseHandle(handle);
        }
    }

    class Class6
    {
        public void readfile(string filename, string Username, string DomainName, string Password)
        { 
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token. 
            const int LOGON32_LOGON_INTERACTIVE = 2;
            SafeTokenHandle safeTokenHandle;

            // Call LogonUser to obtain a handle to an access token. 
            bool returnValue = NativeMethods.LogonUser(
                Username, 
                DomainName, 
                Password,
                LOGON32_LOGON_INTERACTIVE, 
                LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);

            if (!returnValue)
            {
                throw new Exception("unable to login as specifed user :" + Username);
            }
            using (WindowsIdentity id =  new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
            using (WindowsImpersonationContext wic = id.Impersonate())
            {
                if (File.Exists(filename))
                {
                    //good to go
                }
            }
        }
    }
}