C#从零开发基于Windows共享文件夹的图片上传服务全流程指南
# C# 图片上传服务开发指南(Windows共享文件夹方式) ## 1. 环境准备 - 安装Visual Studio 2022或更高版本 - 确保.NET 6.0+ SDK已安装 - 配置好共享文件夹访问权限 ## 2. 创建项目 ```csharp // 使用命令行创建Web API项目 dotnet new webapi -n ImageUploadService ``` ## 3. 配置共享文件夹访问 在appsettings.json中添加配置: ```json { "SharedFolderSettings": { "NetworkPath": "\\\\server\\share\\images", "LocalCachePath": "C:\\Temp\\ImageCache", "Domain": "yourdomain", "Username": "serviceaccount", "Password": "password" } } ``` ## 4. 实现共享文件夹访问类 ```csharp using System.IO; using Microsoft.Extensions.Options; public class SharedFolderAccess { private readonly SharedFolderSettings _settings; public SharedFolderAccess(IOptions<SharedFolderSettings> settings) { _settings = settings.Value; } public async Task SaveImageAsync(IFormFile file, string fileName) { // 确保本地缓存目录存在 if (!Directory.Exists(_settings.LocalCachePath)) { Directory.CreateDirectory(_settings.LocalCachePath); } // 先保存到本地 var localPath = Path.Combine(_settings.LocalCachePath, fileName); using (var stream = new FileStream(localPath, FileMode.Create)) { await file.CopyToAsync(stream); } // 复制到共享文件夹 CopyToSharedFolder(localPath, fileName); } private void CopyToSharedFolder(string localPath, string fileName) { using (new NetworkConnection(_settings.NetworkPath, new NetworkCredential(_settings.Username, _settings.Password, _settings.Domain))) { var sharedPath = Path.Combine(_settings.NetworkPath, fileName); File.Copy(localPath, sharedPath, overwrite: true); } } } // 网络连接辅助类 public class NetworkConnection : IDisposable { [DllImport("mpr.dll", CharSet = CharSet.Unicode)] private static extern int WNetAddConnection2( ref NETRESOURCE netResource, string password, string username, int flags); [DllImport("mpr.dll")] private static extern int WNetCancelConnection2( string name, int flags, bool force); private readonly string _networkName; public NetworkConnection(string networkPath, NetworkCredential credentials) { var netResource = new NETRESOURCE { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplayType.Share, RemoteName = networkPath }; var result = WNetAddConnection2( ref netResource, credentials.Password, credentials.UserName, 0); if (result != 0) { throw new Win32Exception(result, "Failed to connect to network share"); } _networkName = networkPath; } public void Dispose() { WNetCancelConnection2(_networkName, 0, true); } [StructLayout(LayoutKind.Sequential)] private struct 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 { Connected = 1, GlobalNetwork, Remembered, Recent, Context } public enum ResourceType { Any = 0, Disk = 1, Print = 2, Reserved = 8, } public enum ResourceDisplayType { Generic = 0x0, Domain = 0x01, Server = 0x02, Share = 0x03, File = 0x04, Group = 0x05, Network = 0x06, Root = 0x07, Shareadmin = 0x08, Directory = 0x09, Tree = 0x0a, Ndscontainer = 0x0b } } ``` ## 5. 创建控制器 ```csharp using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class ImageUploadController : ControllerBase { private readonly SharedFolderAccess _sharedFolderAccess; public ImageUploadController(SharedFolderAccess sharedFolderAccess) { _sharedFolderAccess = sharedFolderAccess; } [HttpPost] public async Task<IActionResult> UploadImage(IFormFile file) { if (file == null || file.Length == 0) { return BadRequest("No file uploaded"); } var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}"; try { await _sharedFolderAccess.SaveImageAsync(file, fileName); return Ok(new { FileName = fileName }); } catch (Exception ex) { return StatusCode(500, $"Internal server error: {ex.Message}"); } } } ``` ## 6. 注册服务 在Program.cs中添加: ```csharp builder.Services.Configure<SharedFolderSettings>(builder.Configuration.GetSection("SharedFolderSettings")); builder.Services.AddScoped<SharedFolderAccess>(); ``` ## 7. 测试服务 使用Postman或Swagger测试上传功能: - 发送POST请求到/api/ImageUpload - 选择form-data方式,key为"file",value选择图片文件 ## 8. 部署选项 - 发布为Windows服务 - 使用IIS托管 - 使用Kestrel自托管 ## 9. 安全考虑 - 添加文件类型验证 - 实现文件大小限制 - 考虑添加JWT认证 ## 10. 扩展功能 - 添加缩略图生成 - 实现图片元数据提取 - 添加日志记录 ## 注意事项 1. 共享文件夹权限需要正确配置,确保服务账户有读写权限 2. 大文件上传需要考虑分块上传和进度跟踪 3. 文件名冲突处理需要特别注意,建议使用GUID作为文件名 ######[AI写代码神器 | 1403点数解答 | 2025-04-17 11:53:13]
- PHP 开发必知:操作目录的 10 个常用函数全解析(百度文心 | 420点数解答 | 2023-11-09 17:58:57)278
- 工程师必知!Monkey 流程助力软件稳定性与可靠性提升(百度文心 | 388点数解答 | 2023-11-09 18:28:07)295
- 工程师揭秘:重要 APP 从需求到上线全流程攻略(百度文心 | 334点数解答 | 2023-11-09 18:31:47)299
- DBA 必备:Linux 与 Windows 系统开启和停止 MySQL 服务全攻略(百度文心 | 263点数解答 | 2023-11-09 17:59:40)312
- MATLAB 实现:自定义输入信号与频率的时域采样定理演示系统(字节豆包 | 417点数解答 | 2024-12-17 20:28:04)293
- 基于 LPC1114 的多功能电子钟:强大功能+完整代码揭秘!(字节豆包 | 787点数解答 | 2025-05-11 21:01:44)235
- 基于 LPC1114 的多功能电子钟:从功能设计到代码框架全揭秘(字节豆包 | 532点数解答 | 2025-05-15 08:32:18)154
- 基于LPC1114的多功能电子钟:从设计方案到完整代码大揭秘!(字节豆包 | 3363点数解答 | 2025-05-15 23:37:14)254
- 基于LPC1114的多功能电子钟:设计方案、硬件框图与完整代码大揭秘(字节豆包 | 561点数解答 | 2025-05-22 17:56:20)169
- DESKTOP-IG9NT74 设备详细配置大揭秘! (字节豆包 | 38点数解答 | 2026-02-07 18:22:48)53
- Java顺序表源码深度解析:从内存布局到扩容机制与Windows实战指南(阿里通义 | 2528点数解答 | 2026-04-01 10:06:46)23
- Python开发:四大方法教你尝试绕过图片、视频爬取防盗链! (阿里通义 | 378点数解答 | 2023-11-08 00:54:44)243