c#中假设我有一个txt文档,怎么做到一个程序写入的同时另一个程序可以读取

c#中假设我有一个txt文档,怎么做到一个程序写入的同时另一个程序可以读取

温馨提示:有其他疑问可加咨询
1、效果如下
1)在后台执行一个方法,每秒都往txt文件写入信息
2)同时在页面定时读取内容

img

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>

可以每写入一段,就保存一个副本,另一个程序读取副本就行

你是不是想实现一个类似Hoo WinTail程序 类似于日志查看工具,实时显示更新?