C#上传txt文档将小说 txt 按章节拆分
时间: 2023-07-27 07:18:43 浏览: 78
实现将上传的小说txt文档按章节拆分的功能,可以结合ASP.NET MVC和C#实现。下面是一个简单的示例代码,可以将上传的小说txt文件按照章节拆分为多个单独的txt文件,并按照章节命名:
Controller代码:
```csharp
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace NovelSplitter.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0 && file.ContentType == "text/plain")
{
try
{
// 读取上传的小说txt文件内容
string novelText = string.Empty;
using (StreamReader reader = new StreamReader(file.InputStream, Encoding.UTF8))
{
novelText = reader.ReadToEnd();
}
// 按章节拆分并保存为单独的txt文件
string[] chapters = novelText.Split(new string[] { "第" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 1; i < chapters.Length; i++)
{
string chapterText = chapters[i];
int endIndex = chapterText.IndexOf("章");
string chapterTitle = "第" + chapterText.Substring(0, endIndex) + "章";
chapterText = chapterText.Substring(endIndex + 1);
// 将章节文本保存到单独的txt文件中
string chapterFilePath = Path.Combine(Server.MapPath("~/App_Data"), chapterTitle + ".txt");
System.IO.File.WriteAllText(chapterFilePath, chapterText, Encoding.UTF8);
}
ViewBag.Message = "小说已按章节拆分并保存为单独的txt文件。";
}
catch (Exception ex)
{
ViewBag.Message = "上传失败,请重试。" + ex.Message;
}
}
else
{
ViewBag.Message = "请上传小说txt文件。";
}
return View("Index");
}
}
}
```
View代码:
```html
@{
ViewBag.Title = "上传小说";
}
<h2>上传小说</h2>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-group">
<label for="novelFile">选择小说文件</label>
<input type="file" name="file" id="novelFile">
</div>
<button type="submit" class="btn btn-primary">上传</button>
}
@if (ViewBag.Message != null)
{
<div class="alert alert-info">@ViewBag.Message</div>
}
```
使用方法:
1. 将上述代码保存为HomeController.cs文件,并将其拷贝到MVC项目中;
2. 在MVC项目中创建一个名为Index.cshtml的视图文件,并将上述View代码复制到该文件中;
3. 在MVC项目中创建一个名为App_Data的文件夹,用于存储拆分后的小说txt文件;
4. 运行MVC项目,访问Index视图;
5. 选择要上传的小说txt文件并点击“上传”按钮;
6. 程序将会按照章节拆分小说txt文件,并将各章节保存为单独的txt文件,保存在App_Data文件夹中;
7. 程序将会返回上传结果信息。