简体   繁体   English

如何在 c# MVC 中读取 txt 文件

[英]How to read txt file in c# MVC

Hey guys i need to solve this problem and I am completely lost.嘿伙计们,我需要解决这个问题,我完全迷路了。

  1. In root application create txt file, for example addresses.txt a in there will be dates in format: Name;Path;number_of_days;在根应用程序中创建 txt 文件,例如addresses.txt a 中的日期格式为:Name;Path;number_of_days;

2: In method Index load this.txt, where could be 10 rows with addresses. 2:在方法 Index 中加载 this.txt,其中可能是 10 行地址。 I need to load every row with string.Split separator will be semicolon(;) This will be load to List object.我需要用字符串加载每一行。拆分分隔符将是分号(;)这将加载到列表 object。 Then it will go through the foreach and you will go through the individual addresses via File.Getfiles(), where the input parameter is the directory.然后它将通过 foreach 将 go 并通过 File.Getfiles() 将 go 通过各个地址,其中输入参数是目录。 your files will be loaded, which you pass and if neither of them is younger than number_of_days, you note the error for this entry您的文件将被加载,您传递,如果它们都不小于 number_of_days,您会注意到此条目的错误

You can use the following method to read a .txt file from the root folder:您可以使用以下方法从根文件夹中读取.txt文件:

    public string LoadTextFile()
    {
        string response = string.Empty;
        try
        {
            string myTxtFile = System.Web.Hosting.HostingEnvironment.MapPath("~/addresses.txt");
            if (File.Exists(myTxtFile))
            {
                using (StreamReader reader = new StreamReader(myTxtFile))
                {
                    string content = reader.ReadToEnd();
                    response = content;
                }
            }
            else
            {
                response = "File not found, error msg :" + myTxtFile;
            }
        }
        catch (Exception ex)
        {
            response= "Error in getting function LoadTextFile, Error msg :" + ex.Message;
        }

        return response;
    }

Your response string will contain the contents from the file that is read.您的response字符串将包含所读取文件中的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM