酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

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]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]