Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从网络共享访问受密码保护的文件?_C#_Asp.net - Fatal编程技术网

C# 如何从网络共享访问受密码保护的文件?

C# 如何从网络共享访问受密码保护的文件?,c#,asp.net,C#,Asp.net,我遇到了一个问题,我必须从网络共享位置获取受密码保护的文件夹的内容(文件和子目录)。 给定,我有访问文件夹的密码和访问该位置的文件路径。我如何实现这一点 假设这是共享网络- \服务器\Sharedfiles\PasswordProtectedFolder 我想获取其中的内容列表。您可以使用下面的代码从UNC路径访问文件 public static class NetworkShare { /// <summary> /// Connec

我遇到了一个问题,我必须从网络共享位置获取受密码保护的文件夹的内容(文件和子目录)。 给定,我有访问文件夹的密码和访问该位置的文件路径。我如何实现这一点

假设这是共享网络- \服务器\Sharedfiles\PasswordProtectedFolder

我想获取其中的内容列表。

您可以使用下面的代码从UNC路径访问文件

    public static class NetworkShare
    {
        /// <summary>
        /// Connects to the remote share
        /// </summary>
        /// <returns>Null if successful, otherwise error message.</returns>
        public static string ConnectToShare(string uri, string username, string password)
        {
            //Create netresource and point it at the share
            var nr = new Netresource
            {
                dwType = ResourcetypeDisk,
                lpRemoteName = uri
            };

            //Create the share
            var ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

            //Check for errors
            return ret == NoError ? null : GetError(ret);
        }

        /// <summary>
        /// Remove the share from cache.
        /// </summary>
        /// <returns>Null if successful, otherwise error message.</returns>
        public static string DisconnectFromShare(string uri, bool force)
        {
            //remove the share
            var ret = WNetCancelConnection(uri, force);

            //Check for errors
            return ret == NoError ? null : GetError(ret);
        }

        #region P/Invoke Stuff
        [DllImport("Mpr.dll")]
        private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            Netresource lpNetResource,
            string lpPassword,
            string lpUserId,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
            );

        [DllImport("Mpr.dll")]
        private static extern int WNetCancelConnection(
            string lpName,
            bool fForce
            );

        [StructLayout(LayoutKind.Sequential)]
        private class Netresource
        {
            public int dwScope = 0;
            public int dwType = 0;
            public int dwDisplayType = 0;
            public int dwUsage = 0;
            public string lpLocalName = "";
            public string lpRemoteName = "";
            public string lpComment = "";
            public string lpProvider = "";
        }

        #region Consts
        const int ResourcetypeDisk = 0x00000001;
        const int ConnectUpdateProfile = 0x00000001;
        #endregion

        #region Errors
        const int NoError = 0;

        const int ErrorAccessDenied = 5;
        const int ErrorAlreadyAssigned = 85;
        const int ErrorBadDevice = 1200;
        const int ErrorBadNetName = 67;
        const int ErrorBadProvider = 1204;
        const int ErrorCancelled = 1223;
        const int ErrorExtendedError = 1208;
        const int ErrorInvalidAddress = 487;
        const int ErrorInvalidParameter = 87;
        const int ErrorInvalidPassword = 1216;
        const int ErrorMoreData = 234;
        const int ErrorNoMoreItems = 259;
        const int ErrorNoNetOrBadPath = 1203;
        const int ErrorNoNetwork = 1222;
        const int ErrorSessionCredentialConflict = 1219;

        const int ErrorBadProfile = 1206;
        const int ErrorCannotOpenProfile = 1205;
        const int ErrorDeviceInUse = 2404;
        const int ErrorNotConnected = 2250;
        const int ErrorOpenFiles = 2401;

        private struct ErrorClass
        {
            public int Num;
            public string Message;
            public ErrorClass(int num, string message)
            {
                this.Num = num;
                this.Message = message;
            }
        }

        private static readonly ErrorClass[] ErrorList = new ErrorClass[] {
        new ErrorClass(ErrorAccessDenied, "Error: Access Denied"),
        new ErrorClass(ErrorAlreadyAssigned, "Error: Already Assigned"),
        new ErrorClass(ErrorBadDevice, "Error: Bad Device"),
        new ErrorClass(ErrorBadNetName, "Error: Bad Net Name"),
        new ErrorClass(ErrorBadProvider, "Error: Bad Provider"),
        new ErrorClass(ErrorCancelled, "Error: Cancelled"),
        new ErrorClass(ErrorExtendedError, "Error: Extended Error"),
        new ErrorClass(ErrorInvalidAddress, "Error: Invalid Address"),
        new ErrorClass(ErrorInvalidParameter, "Error: Invalid Parameter"),
        new ErrorClass(ErrorInvalidPassword, "Error: Invalid Password"),
        new ErrorClass(ErrorMoreData, "Error: More Data"),
        new ErrorClass(ErrorNoMoreItems, "Error: No More Items"),
        new ErrorClass(ErrorNoNetOrBadPath, "Error: No Net Or Bad Path"),
        new ErrorClass(ErrorNoNetwork, "Error: No Network"),
        new ErrorClass(ErrorBadProfile, "Error: Bad Profile"),
        new ErrorClass(ErrorCannotOpenProfile, "Error: Cannot Open Profile"),
        new ErrorClass(ErrorDeviceInUse, "Error: Device In Use"),
        new ErrorClass(ErrorExtendedError, "Error: Extended Error"),
        new ErrorClass(ErrorNotConnected, "Error: Not Connected"),
        new ErrorClass(ErrorOpenFiles, "Error: Open Files"),
        new ErrorClass(ErrorSessionCredentialConflict, "Error: Credential Conflict"),
    };

        private static string GetError(int errNum)
        {
            foreach (var er in ErrorList)
            {
                if (er.Num == errNum) return er.Message;
            }
            return "Error: Unknown, " + errNum;
        }
        #endregion

        #endregion

        public static byte[] GetFileBytes(string serverSharedPath,string fileName, string userName, string password)
        {
            DisconnectFromShare($@"{serverSharedPath}", true); //Disconnect in case we are currently connected with our credentials;
            var connectToShare = ConnectToShare($@"{serverSharedPath}", userName, password); //Connect with the new credentials
            if (!string.IsNullOrEmpty(connectToShare))
                return new byte[0];
            if (!Directory.Exists($@"{serverSharedPath}"))
                return new byte[0];
            if (!File.Exists($@"{serverSharedPath}\{fileName}"))
                return new byte[0];
            return File.ReadAllBytes(
                $@"{serverSharedPath}\{fileName}");
        }

        public static bool DeleteFileFromSharedPath(string serverSharedPath, string fileName, string userName,
            string password)
        {
            DisconnectFromShare($@"{serverSharedPath}", true); //Disconnect in case we are currently connected with our credentials;
            var connectToShare = ConnectToShare($@"{serverSharedPath}", userName, password); //Connect with the new credentials
            if (!string.IsNullOrEmpty(connectToShare))
                return false;
            if (File.Exists($@"{serverSharedPath}\{fileName}"))
            {
                try
                {
                    File.Delete($@"{serverSharedPath}\{fileName}");
                    return true;
                }
                catch (IOException exception)
                {
                    return false;
                }
            }
            return true;
        }

        public static bool WriteFileByte(string serverSharedPath, string fileName, byte[] fileBytes, string userName, string password)
        {
            DisconnectFromShare($@"{serverSharedPath}",
                true); //Disconnect in case we are currently connected with our credentials;
            var connectToShare =
                ConnectToShare($@"{serverSharedPath}", userName, password); //Connect with the new credentials
            if (!string.IsNullOrEmpty(connectToShare))
                return false;
            if (!Directory.Exists($@"{serverSharedPath}"))
                return false;
            if (File.Exists($@"{serverSharedPath}\{fileName}"))
                File.Delete($@"{serverSharedPath}\{fileName}");

            File.WriteAllBytes($@"{serverSharedPath}\{fileName}", fileBytes);
            return true;
        }


        public static bool IsNetworkConnectivityOk(string serverSharedPath, string userName, string password)
        {
            DisconnectFromShare($@"{serverSharedPath}", true); //Disconnect in case we are currently connected with our credentials;
            var connectToShare = ConnectToShare($@"{serverSharedPath}", userName, password); //Connect with the new credentials
            if (!string.IsNullOrEmpty(connectToShare))
                return false;
            if (!Directory.Exists($@"{serverSharedPath}"))
                return false;
            DisconnectFromShare($@"{serverSharedPath}", false); //Disconnect from the server.
            return true;
        }
    }
公共静态类网络共享
{
/// 
///连接到远程共享
/// 
///如果成功,则为Null,否则为错误消息。
公共静态字符串ConnectToShare(字符串uri、字符串用户名、字符串密码)
{
//创建netresource并将其指向共享
var nr=新的网络资源
{
dwType=ResourcetypeDisk,
lpRemoteName=uri
};
//创建共享
var ret=WNetUseConnection(IntPtr.Zero,nr,密码,用户名,0,null,null,null);
//检查错误
return ret==NoError?null:GetError(ret);
}
/// 
///从缓存中删除共享。
/// 
///如果成功,则为Null,否则为错误消息。
公共静态字符串DisconnectFromShare(字符串uri,bool-force)
{
//删除共享
var ret=WNetCancelConnection(uri,force);
//检查错误
return ret==NoError?null:GetError(ret);
}
#地区P/P
[DllImport(“Mpr.dll”)]
私有静态外部int WNetUseConnection(
IntPtr hwndOwner,
Netresource lpNetResource,
字符串密码,
字符串lpUserId,
int dwFlags,
字符串lpAccessName,
字符串大小,
字符串lpResult
);
[DllImport(“Mpr.dll”)]
私有静态外部内部所有者取消连接(
字符串名称,
布尔福斯
);
[StructLayout(LayoutKind.Sequential)]
私有类网络资源
{
公共int dwScope=0;
公共int dwType=0;
public int dwDisplayType=0;
公共int dwUsage=0;
公共字符串lpLocalName=“”;
公共字符串lpRemoteName=“”;
公共字符串lpComment=“”;
公共字符串lpProvider=“”;
}
#区域常数
const int ResourcetypeDisk=0x00000001;
const int ConnectUpdateProfile=0x00000001;
#端区
#区域误差
常数int NoError=0;
const int ErrorAccessDenied=5;
常数int ERRORALDEASSIGNED=85;
常数int ERRORBADEVENT=1200;
const int ErrorBadNetName=67;
常量int ErrorBadProvider=1204;
常数int ERROR CANCELED=1223;
常量int ERRORSTENDERROR=1208;
const int ErrorInvalidAddress=487;
常数int ErrorInvalidParameter=87;
const int ErrorInvalidPassword=1216;
常数int ErrorMoreData=234;
const int errornomoreims=259;
常量int ErrorNoNetOrBadPath=1203;
常数int ErrorNoNetwork=1222;
const int ErrorSessionCredentialConflict=1219;
常数int ErrorBadProfile=1206;
常数int ErrorCannotOpenProfile=1205;
常数int ERROR DEVICEINUSE=2404;
常数int ErrorNotConnected=2250;
const int ErrorOpenFiles=2401;
私有结构错误类
{
公共整数;
公共字符串消息;
公共错误类(整数,字符串消息)
{
this.Num=Num;
this.Message=消息;
}
}
私有静态只读ErrorClass[]ErrorList=新ErrorClass[]{
新的ErrorClass(ErrorAccessDenied,“错误:访问被拒绝”),
新的ErrorClass(ErrorAlreadyAssigned,“错误:已分配”),
新的ErrorClass(ErrorBadDevice,“错误:坏设备”),
新的ErrorClass(ErrorBadNetName,“错误:错误的网络名”),
新的ErrorClass(ErrorBadProvider,“错误:错误提供程序”),
新的ErrorClass(ErrorCancelled,“Error:Cancelled”),
新的ErrorClass(ErrorExtendedError,“错误:扩展错误”),
新的ErrorClass(ErrorInvalidAddress,“错误:无效地址”),
新的ErrorClass(ErrorInvalidParameter,“错误:无效参数”),
新的ErrorClass(ErrorInvalidPassword,“错误:无效密码”),
新的ErrorClass(ErrorMoreData,“错误:更多数据”),
新的ErrorClass(ErrorNoMoreItems,“错误:无更多项”),
新的ErrorClass(ErrorNoNetOrBadPath,“错误:无网络或错误路径”),
新的ErrorClass(ErrorNoNetwork,“错误:无网络”),
新的ErrorClass(ErrorBadProfile,“错误:错误配置文件”),
新的ErrorClass(ErrorCannotOpenProfile,“错误:无法打开配置文件”),
新的ErrorClass(ErrorDeviceUse,“错误:正在使用的设备”),
新的ErrorClass(ErrorExtendedError,“错误:扩展错误”),
新的ErrorClass(ErrorNotConnected,“错误:未连接”),
新的ErrorClass(ErrorOpenFiles,“错误:打开文件”),
新的ErrorClass(ErrorSessionCredentialConflict,“错误:凭证冲突”),
};
私有静态字符串GetError(int errNum)
{
foreach(错误列表中的变量)
{
if(er.Num==errNum)返回er.Message;
}
返回“错误:未知,”+errNum;
}
#端区
#端区
公共静态字节[]GetFileBytes(字符串服务器共享路径、字符串文件名、字符串用户名、字符串密码)
{
DisconnectFromShare($@“{serverSharedPath}”,true);//如果我们当前使用凭据连接,请断开连接;
变量