C# 远程连接共享文件夹下载文件

Posted 说不出来

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 远程连接共享文件夹下载文件相关的知识,希望对你有一定的参考价值。

远程连接FTP并下载文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
namespace MyFtp
{
    public class FtpHandle
    {
        public string strUserName;
        public string strUserPwd;
        public string strUrl;
        public FtpWebRequest request;
 
        public FtpHandle(string strUserName,string strUserPwd,string strIPAdd,string strPort,string strFolder)
        {
            this.strUserName = strUserName;
            this.strUserPwd = strUserPwd;
            this.strUrl = @"ftp://" + strIPAdd + @":" + strPort + @"/" + strFolder;
        }
 
        //创建FTP连接
        private void Connect()
        {
            this.request = FtpWebRequest.Create(new Uri(this.strUrl)) as FtpWebRequest;
            this.request.UseBinary = true;   //指定数据传输类型为二进制
            this.request.Credentials = new NetworkCredential(this.strUserName,strUserPwd);  //设置用户名和密码
        }
 
        /// <summary>
        /// 从ftp服务器下载文件的功能
        /// </summary>
        /// <param name="strTargetFile">本地目标路径</param>
        /// <returns></returns>
        public bool Download(string strTargetFile)
        {
            try
            {                
                if (File.Exists(strTargetFile))
                {
                    File.Delete(strTargetFile);//文件夹存在同名文件,直接删除同名文件
                }
                Connect();
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                FileStream outputStream = new FileStream(strTargetFile, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();                
                return true;
            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }
    }
}

  远程共享文件夹并下载文件

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
 
namespace WindowsFormsApp1
{
    public enum RESOURCE_SCOPE
    {
        RESOURCE_CONNECTED = 1,
        RESOURCE_GLOBALNET = 2,
        RESOURCE_REMEMBERED = 3,
        RESOURCE_RECENT = 4,
        RESOURCE_CONTEXT = 5
    }
 
    public enum RESOURCE_TYPE
    {
        RESOURCETYPE_ANY = 0,
        RESOURCETYPE_DISK = 1,
        RESOURCETYPE_PRINT = 2,
        RESOURCETYPE_RESERVED = 8,
    }
 
    public enum RESOURCE_USAGE
    {
        RESOURCEUSAGE_CONNECTABLE = 1,
        RESOURCEUSAGE_CONTAINER = 2,
        RESOURCEUSAGE_NOLOCALDEVICE = 4,
        RESOURCEUSAGE_SIBLING = 8,
        RESOURCEUSAGE_ATTACHED = 16,
        RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
    }
 
    public enum RESOURCE_DISPLAYTYPE
    {
        RESOURCEDISPLAYTYPE_GENERIC = 0,
        RESOURCEDISPLAYTYPE_DOMAIN = 1,
        RESOURCEDISPLAYTYPE_SERVER = 2,
        RESOURCEDISPLAYTYPE_SHARE = 3,
        RESOURCEDISPLAYTYPE_FILE = 4,
        RESOURCEDISPLAYTYPE_GROUP = 5,
        RESOURCEDISPLAYTYPE_NETWORK = 6,
        RESOURCEDISPLAYTYPE_ROOT = 7,
        RESOURCEDISPLAYTYPE_SHAREADMIN = 8,
        RESOURCEDISPLAYTYPE_DIRECTORY = 9,
        RESOURCEDISPLAYTYPE_TREE = 10,
        RESOURCEDISPLAYTYPE_NDSCONTAINER = 11
    }
 
    [StructLayout(LayoutKind.Sequential)]
    public struct NETRESOURCE
    {
        public RESOURCE_SCOPE dwScope;
        public RESOURCE_TYPE dwType;
        public RESOURCE_DISPLAYTYPE dwDisplayType;
        public RESOURCE_USAGE dwUsage;
 
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpLocalName;
 
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpRemoteName;
 
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpComment;
 
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpProvider;
    }
 
    public class NetworkConnection
    {
        //创建网络连接
        [DllImport("mpr.dll")]
        public static extern int WNetAddConnection2A(NETRESOURCE[] lpNetResource, string lpPassword, string lpUserName, int dwFlags);
 
        //取消现有网络连接
        [DllImport("mpr.dll")]
        public static extern int WNetCancelConnection2A(string sharename, int dwFlags, int fForce);
 
        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="remotePath">文件夹路径</param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static int Connect(string remotePath, string username, string password)
        {
            //必须是\\\\127.0.1.1\\test格式,最后不能带斜杠
            if (remotePath.EndsWith("\\\\"))
            {
                remotePath = remotePath.Substring(0, remotePath.Length - 1);
            }
            NETRESOURCE[] share_driver = new NETRESOURCE[1];
            share_driver[0].dwScope = RESOURCE_SCOPE.RESOURCE_GLOBALNET;
            share_driver[0].dwType = RESOURCE_TYPE.RESOURCETYPE_DISK;
            share_driver[0].dwDisplayType = RESOURCE_DISPLAYTYPE.RESOURCEDISPLAYTYPE_SHARE;
            share_driver[0].dwUsage = RESOURCE_USAGE.RESOURCEUSAGE_CONNECTABLE;
            share_driver[0].lpRemoteName = remotePath;
            //连接前先断开一次,否则会报错
            Disconnect(remotePath);
            int ret = WNetAddConnection2A(share_driver, password, username, 1);
            return ret;
        }
 
        /// <summary>
        /// 断开远程共享文件夹
        /// </summary>
        /// <param name="remotePath"></param>
        /// <returns></returns>
        public static int Disconnect(string remotePath)
        {
            try
            {
                //必须是\\\\127.0.1.1\\test格式,最后不能带斜杠
                if (remotePath.EndsWith("\\\\"))
                {
                    remotePath = remotePath.Substring(0, remotePath.Length - 1);
                }
                int status = WNetCancelConnection2A(remotePath, 1, 1);
                return status;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
 
        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public static string GetErrorString(int status)
        {
            string strDesc = string.Empty;
            switch (status)
            {
                case 0:
                    strDesc = "Success";
                    break;
                case 5:
                    strDesc = "网络访问拒绝";
                    break;
                case 86:
                case 1326:
                    strDesc = "无效的用户名或密码";
                    break;
                case 1203:
                    strDesc = "无效的网络路径";
                    break;
                case 1219:
                    strDesc = "提供的凭据与已存在的凭据集冲突";
                    break;
                default:
                    strDesc = "无法连接网络路径,错误代码:";
                    break;
            }
            return strDesc;
        }
 
        /// <summary>
        /// cmd命令删除本机网络磁盘缓存用户
        /// </summary>
        public static void DelCacheUser()
        {
            try
            {
                string strCommand = @"NET USE * /DELETE /Y";
                Process p = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe";
                startInfo.Arguments = "/C " + strCommand;
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardInput = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow = true;
                p.StartInfo = startInfo;
                p.Start();
                p.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
 
    public class DiskHandle
    {
        public string userName;
        public string passWord;        
 
        public DiskHandle(string strUserName, string strPwd)
        {
            this.userName = strUserName;
            this.passWord = strPwd;            
        }
 
        /// <summary>
        /// 共享路径下载文件
        /// </summary>
        /// <param name="strFullPath">远程文件全路径</param>
        /// <param name="strTargetFile">保存到本地的文件路径</param>
        /// <param name="errorInfo">错误信息</param>
        /// <returns></returns>
        public bool DownLoad(string strFullPath, string strTargetFile, out string errorInfo)
        {
            errorInfo = string.Empty;
            try
            {
                string strRemotePath = Path.GetDirectoryName(strFullPath);
                if (!File.Exists(strFullPath))
                {
                    return false;
                }
                int status = NetworkConnection.Connect(strRemotePath, this.userName, this.passWord);  //连接远程共享文件夹
                if (status != 0)
                {
                    errorInfo = strFullPath + "," + NetworkConnection.GetErrorString(status);
                    return false;
                }
                else
                {                    
                    if (File.Exists(strTargetFile))
                    {
                        File.Delete(strTargetFile);//文件夹存在同名文件,直接删除同名文件
                    }
 
                    using (FileStream fileStream = new FileStream(strFullPath, FileMode.Open))
                    {
                        //读取
                        int readCount;
                        int bufferSize = 2048;
                        byte[] buffer = new byte[bufferSize];
                        readCount = fileStream.Read(buffer, 0, buffer.Length);
                        FileStream outputStream = new FileStream(strTargetFile, FileMode.Create);
                        while (readCount > 0)
                        {
                            outputStream.Write(buffer, 0, readCount);
                            readCount = fileStream.Read(buffer, 0, bufferSize);
                        }
                        outputStream.Close();
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

  

以上是关于C# 远程连接共享文件夹下载文件的主要内容,如果未能解决你的问题,请参考以下文章

是否可以使用托管标识从 C# 控制台代码连接 Azure 文件共享(存储帐户)

如何使用 C# 在远程 Windows 机器上创建共享文件夹?

通过“远程桌面连接”工具,共享本机磁盘到远程服务器

什么软件可以实现远程文件夹共享。

C#利用ICSharpCode将远程文件打包并下载

java操作远程共享目录