c#中假设我有一个txt文档,怎么做到一个程序写入的同时另一个程序可以读取
3条回答 默认 最新
关注 温馨提示:有其他疑问可加咨询
1、效果如下
1)在后台执行一个方法,每秒都往txt文件写入信息
2)同时在页面定时读取内容2、代码如下
1)后端代码using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test.core._31.Controllers { public class ReadWriteTxtController : Controller { public static string myLocalPath = @"E:\test.txt"; public static void WriteFile() { try { var FilePath = myLocalPath; var now = DateTime.Now; string Content = now.ToString("yyyy年MM月dd日 HH:mm:ss\r\n"); System.IO.File.AppendAllText(FilePath, Content); } catch (Exception exception) { } finally { } } static string ReadFile() { string content = ""; try { using (StreamReader sr = new StreamReader(myLocalPath, Encoding.Default)) { string line; while ((line = sr.ReadLine()) != null) { content = line.ToString() + "\r\n" + content; } } } catch (Exception exception) { } finally { } return content; } public IActionResult Index() { Task.Run(() => { while (true) { System.Threading.Thread.Sleep(1000); WriteFile(); } }); return View(); } public IActionResult Read() { string test1 = ReadFile(); test1 = test1.Replace("\r\n", "<br/>"); return Json(test1); } } }
2)前端代码
@{ Layout = null; } <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no" /> <div id="info"> </div> <script src="https://libs.baidu.com/jquery/2.0.0/jquery.js"></script> <script type="text/javascript"> $(function () { setInterval(function () { $.ajax({ url: '/ReadWriteTxt/Read', data: {}, dataType: 'json', type: 'test', success: function (data) { $("#info").html(data); } }); }, 500); }); </script>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 机器学习能否像多层线性模型一样处理嵌套数据
- ¥20 西门子S7-Graph,S7-300,梯形图
- ¥50 用易语言http 访问不了网页
- ¥50 safari浏览器fetch提交数据后数据丢失问题
- ¥15 matlab不知道怎么改,求解答!!
- ¥15 永磁直线电机的电流环pi调不出来
- ¥15 用stata实现聚类的代码
- ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
- ¥20 docker里部署springboot项目,访问不到扬声器
- ¥15 netty整合springboot之后自动重连失效