.net core 讀取本地指定目錄下的文件

項目需求git

asp.net core 讀取log目錄下的.log文件,.log文件的內容以下:github

xxx.logapp

------------------------------------------begin---------------------------------
寫入時間:2018-09-11 17:01:48
userid=1000
golds=10
-------------------------------------------end---------------------------------asp.net

一個 begin end 爲一組,同一個.log文件裏 userid 相同的,取寫入時間最大一組值,所需結果以下:async

UserID   Golds   RecordDate 
 1001     20     2018/9/11 17:10:48  
 1000     20     2018/9/11 17:11:48  
 1003     30     2018/9/11 17:12:48  
 1002     10     2018/9/11 18:01:48 
   
 1001     20     2018/9/12 17:10:48  
 1000     30     2018/9/12 17:12:48  
 1002     10     2018/9/12 18:01:48

項目結構
ide

Snai.File.FileOperation  Asp.net core 2.0 網站函數

項目實現網站

新建Snai.File解決方案,在解決方案下新建一個名Snai.File.FileOperation Asp.net core 2.0 空網站ui

把log日誌文件拷備到項目下this

修改Startup類的ConfigureServices()方法,註冊訪問本地文件所需的服務,到時在中間件中經過構造函數注入添加到中間件,這樣就能夠在一個地方控制文件的訪問路徑(也就是應用程序啓動的時候)

public void ConfigureServices(IServiceCollection services)
{
  services.AddSingleton<IFileProvider>(new PhysicalFileProvider(Directory.GetCurrentDirectory()));
}

新建 Middleware 文件夾,在 Middleware下新建 Entity 文件夾,新建 UserGolds.cs 類,用來保存讀取的日誌內容,代碼以下

namespace Snai.File.FileOperation.Middleware.Entity
{
    public class UserGolds
    {
        public UserGolds()
        {
            RecordDate = new DateTime(1970, 01, 01);
            UserID = 0;
            Golds = 0;
        }

        public DateTime RecordDate { get; set; }
        public int UserID { get; set; }
        public int Golds { get; set; }
    }
}

 在 Middleware 下新建 FileProviderMiddleware.cs 中間件類,用於讀取 log 下全部日誌文件內容,並整理成所需的內容格式,代碼以下

namespace Snai.File.FileOperation.Middleware
{
    public class FileProviderMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IFileProvider _fileProvider;

        public FileProviderMiddleware(RequestDelegate next, IFileProvider fileProvider)
        {
            _next = next;
            _fileProvider = fileProvider;
        }

        public async Task Invoke(HttpContext context)
        {
            var output = new StringBuilder("");
            //ResolveDirectory(output, "", "");
            ResolveFileInfo(output, "log", ".log");

            await context.Response.WriteAsync(output.ToString());
        }

        //讀取目錄下全部文件內容
        private void ResolveFileInfo(StringBuilder output, string path, string suffix)
        {
            output.AppendLine("UserID    Golds    RecordDate");

            IDirectoryContents dir = _fileProvider.GetDirectoryContents(path);
            foreach (IFileInfo item in dir)
            {
                if (item.IsDirectory)
                {
                    ResolveFileInfo(output,
                        item.PhysicalPath.Substring(Directory.GetCurrentDirectory().Length),
                        suffix);
                }
                else
                {
                    if (item.Name.Contains(suffix))
                    {
                        var userList = new List<UserGolds>();
                        var user = new UserGolds();

                        IFileInfo file = _fileProvider.GetFileInfo(path + "\\" + item.Name);

                        using (var stream = file.CreateReadStream())
                        {
                            using (var reader = new StreamReader(stream))
                            {
                                string content = reader.ReadLine();

                                while (content != null)
                                {
                                    if (content.Contains("begin"))
                                    {
                                        user = new UserGolds();
                                    }
                                    if (content.Contains("寫入時間"))
                                    {
                                        DateTime recordDate;
                                        string strRecordDate = content.Substring(content.IndexOf(":") + 1).Trim();
                                        if (DateTime.TryParse(strRecordDate, out recordDate))
                                        {
                                            user.RecordDate = recordDate;
                                        }
                                    }

                                    if (content.Contains("userid"))
                                    {
                                        int userID;
                                        string strUserID = content.Substring(content.LastIndexOf("=") + 1).Trim();
                                        if (int.TryParse(strUserID, out userID))
                                        {
                                            user.UserID = userID;
                                        }
                                    }

                                    if (content.Contains("golds"))
                                    {
                                        int golds;
                                        string strGolds = content.Substring(content.LastIndexOf("=") + 1).Trim();
                                        if (int.TryParse(strGolds, out golds))
                                        {
                                            user.Golds = golds;
                                        }
                                    }

                                    if (content.Contains("end"))
                                    {
                                        var userMax = userList.FirstOrDefault(u => u.UserID == user.UserID);
                                        if (userMax == null || userMax.UserID <= 0)
                                        {
                                            userList.Add(user);
                                        }
                                        else if (userMax.RecordDate < user.RecordDate)
                                        {
                                            userList.Remove(userMax);
                                            userList.Add(user);
                                        }
                                    }

                                    content = reader.ReadLine();
                                }
                            }
                        }

                        if (userList != null && userList.Count > 0)
                        {
                            foreach (var golds in userList.OrderBy(u => u.RecordDate))
                            {
                                output.AppendLine(golds.UserID.ToString() + "    " + golds.Golds + "    " + golds.RecordDate);
                            }

                            output.AppendLine("");
                        }
                    }
                }
            }
        }

        //讀取目錄下全部文件名
        private void ResolveDirectory(StringBuilder output, string path, string prefix)
        {
            IDirectoryContents dir = _fileProvider.GetDirectoryContents(path);
            foreach (IFileInfo item in dir)
            {
                if (item.IsDirectory)
                {
                    output.AppendLine(prefix + "[" + item.Name + "]");

                    ResolveDirectory(output,
                        item.PhysicalPath.Substring(Directory.GetCurrentDirectory().Length),
                        prefix + "    ");
                }
                else
                {
                    output.AppendLine(path + prefix + item.Name);
                }
            }
        }
    }

    public static class UseFileProviderExtensions
    {
        public static IApplicationBuilder UseFileProvider(this IApplicationBuilder app)
        {
            return app.UseMiddleware<FileProviderMiddleware>();
        }
    }
}

上面有兩個方法 ResolveFileInfo()和ResolveDirectory()

ResolveFileInfo()  讀取目錄下全部文件內容,也就是需求所用的方法

ResolveDirectory() 讀取目錄下全部文件名,是輸出目錄下全部目錄和文件名,不是需求所需但也能夠用

修改Startup類的Configure()方法,在app管道中使用文件中間件服務

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

  app.UseFileProvider();
  
  app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World!");
  });
}

到此全部代碼都已編寫完成

啓動運行項目,獲得所需結果,頁面結果以下

源碼訪問地址:https://github.com/Liu-Alan/Snai.File

相關文章
相關標籤/搜索