C# 远程连接共享文件夹下载文件
远程连接FTP并下载文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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; } } } } |
远程共享文件夹并下载文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | 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; } } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」