1.引言
在当今数字化时代中,文件传输和共享已经变得越来越普及和必要。而构建一个文件服务器可以有效地满足不同人员和团队之间文件共享的需求。本文将介绍如何使用 C#快速手动构建一个简单的文件服务器。
2.创建C#文件服务器
2.1 安装必要的组件
首先,需要安装 .NET Framework。如果选择安装 Visual Studio,则可以把 .NET Framework 一同安装,直接开发。如果使用 Visual Studio Code 进行开发,则需要下载并手动安装 .NET Framework。
2.2 建立C#文件服务器项目
在 Visual Studio 中选择“新建项目” -> “ASP.NET Web 应用程序”,然后选择“ASP.NET Web 应用程序 (.NET Framework)”作为应用程序类型。为项目命名并选择位置后,点击“确定”。
选择“Web API” 作为项目模板,并保证“身份验证”选项为“无身份验证”,单击“创建”按钮。这个时候,会创建一个基础的 Web API 项目。
2.3 实现C#文件服务器功能
添加以下代码以实现文件上传、下载和删除功能。
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FileServer.Controllers
{
[ApiController]
[Route("[controller]")]
public class FileServerController : ControllerBase
{
[HttpPost]
[Route("UploadFile")]
public async Task UploadFile()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources", "Files");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
[HttpGet("{fileName}")]
public async Task DownloadFile(string fileName)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "Files", fileName);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
[HttpDelete("{fileName}")]
public async Task DeleteFile(string fileName)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "Files", fileName);
if (!System.IO.File.Exists(path))
return NotFound();
System.IO.File.Delete(path);
return Ok();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary GetMimeTypes()
{
return new Dictionary()
{
{ ".txt", "text/plain" },
{ ".pdf", "application/pdf" },
{ ".doc", "application/vnd.ms-word" },
{ ".docx", "application/vnd.ms-word" },
{ ".xls", "application/vnd.ms-excel" },
{ ".xlsx", "application/vnd.ms-excel" },
{ ".png", "image/png" },
{ ".jpg", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".gif", "image/gif" },
{ ".csv", "text/csv" },
{ ".zip", "application/zip" },
{ ".rar", "application/x-rar-compressed" },
{ ".apk", "application/vnd.android.package-archive" },
{ ".ipa", "application/vnd.iphone" }
};
}
}
}
2.4 配置C#文件服务器
找到项目中的“Startup.cs”文件,添加以下代码以配置文件服务器:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FileServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0).ConfigureApiBehaviorOptions(options =>
{
options.SuppressMapClientErrors = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
3.测试C#文件服务器
通过创建文件服务器后,我们可以使用如下代码进行测试。如需上传文件, 请将“file”参数替换为实际文件路径。或者您可以获取范例文件进行测试。
private async Task TestFileServer()
{
HttpClient client = new HttpClient();
MultipartFormDataContent formData = new MultipartFormDataContent();
formData.Add(new ByteArrayContent(File.ReadAllBytes("file")), "file", "testfile.txt");
HttpResponseMessage response = await client.PostAsync("http://fileServer/UploadFile", formData);
Console.WriteLine(await response.Content.ReadAsStringAsync());
response = await client.GetAsync("http://fileServer/testfile.txt");
var fileBytes = await response.Content.ReadAsByteArrayAsync();
File.WriteAllBytes("testfile.txt", fileBytes);
response = await client.DeleteAsync("http://fileServer/testfile.txt");
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
4.结论
C# 文件服务器能够方便地搭建一个平台,实现不同用户之间文件的互相传送和共享。通过本文介绍的代码实现,程序员们能够快速地搭建一个简单的文件服务器。