c# 提取电子书内容

这里简单介绍一种方法:

实现思路:chm格式转html,然后提取html中指定的内容。

1.chm转html:

        private void UseCmdFunc(string chmName,string htmlOutPath)
        {
            Process process = new Process();

            // 设置进程启动信息
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "cmd.exe"; // 设置要启动的程序为CMD
            startInfo.RedirectStandardInput = true; // 设置重定向输入流
            startInfo.UseShellExecute = false; // 设置不使用操作系统外壳程序启动进程
            startInfo.CreateNoWindow = true; // 设置不创建窗口

            // 启动进程
            process.StartInfo = startInfo;
            process.Start();

            string htmOutPath = htmlOutPath + @"\html" +                        
            chmName.Replace(".chm","").Replace(htmlOutPath, "") + "html";// 输入命令
            process.StandardInput.WriteLine($@"hh -decompile {htmOutPath} {chmName}"); // 输入dir命令

            // 关闭输入流
            process.StandardInput.Close();

            // 等待命令执行完毕
            process.WaitForExit();
        }

2.读取html内容

private string Readhtml(string htmFilePath)
        {
            var outputText = "";
            try
            {
                 var externsion = Path.GetExtension(file);

                    if (externsion != ".htm" && externsion != ".html")
                        continue;
                    // 创建HtmlDocument对象并加载htm文件
                    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                    htmlDoc.Load(file);

                    var linkNodes = htmlDoc.DocumentNode.SelectNodes("//p");//此处选择需要检索的标签,提取内容即可

                    if (linkNodes != null && linkNodes.Count > 0)
                    {
                        foreach (var node in linkNodes)
                        {
                            string text = node.InnerText.Trim();
                            if (!string.IsNullOrEmpty(text))
                            {
                                sb.AppendLine(text);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("未找到任何数据!");
                    }
                outputText = sb.ToString();                
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误:{ex.Message}");
            }
            return outputText;
        }

此代码使用了HtmlAgilityPack库,引用使用NuGet添加包即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值