简体   繁体   中英

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;

2: In method Index load this.txt, where could be 10 rows with addresses. I need to load every row with string.Split separator will be semicolon(;) This will be load to List 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. 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

You can use the following method to read a .txt file from the root folder:

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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