Skip to content

Read text from file in ASP.NET Core

This article shows some alternatives to read text from a file with C# in ASP.NET Core. You may want to read text from a file to import data or to get input to your application.

Read from CSV file

A CSV file is a text file where the data on each row is separated by comma (,), other characters can be used as seperators. A CSV file can be exported from Excel or Open Office Calc for example.

List<string[]> values = new List<string[]>();
using (StreamReader reader = new StreamReader("D:\\MyFolder\\Files\\case.txt"))
{
    while(!reader.EndOfStream)
    {
        values.Add(reader.ReadLine().Split(','));
    }
}

Read from XML file

XML files is frequently used in different standards and is similar to HTML. The code below shows an example of reading teams from an XML file with group standings.

<standings>
	<team>
		<name>Malmö FF</name>
		<games>7</games>
		<wins>4</wins>
		<ties>2</ties>
		<losses>1</losses>
		<goals>12-7 (5)</goals>
		<points>14</points>
	</team>
	<team>
		<name>IFK Göteborg</name>
		<games>7</games>
		<wins>4</wins>
		<ties>1</ties>
		<losses>2</losses>
		<goals>16-9 (7)</goals>
		<points>13</points>
	</team>
	<team>
		<name>BK Häcken</name>
		<games>7</games>
		<wins>4</wins>
		<ties>1</ties>
		<losses>2</losses>
		<goals>10-4 (6)</goals>
		<points>13</points>
	</team>
</standings>
public class TeamInGroupStanding
{
    #region Variables

    public string name { get; set; }
    public string games { get; set; }
    public string wins { get; set; }
    public string ties { get; set; }
    public string losses { get; set; }
    public string goals { get; set; }
    public string points { get; set; }

    #endregion

    #region Constructors

    public TeamInGroupStanding()
    {
        // Set values for instance variables
        this.name = "";
        this.games = "";
        this.wins = "";
        this.ties = "";
        this.losses = "";
        this.goals = "";
        this.points = "";

    } // End of the constructor

    #endregion

} // End of the class
public IList<TeamInGroupStanding> GetTeamsFromXml(string xmlString)
{
    // Create the list to return
    IList<TeamInGroupStanding> posts = new List<TeamInGroupStanding>(12);

    try
    {
        // Create the xml document
        XDocument xmlDocument = XDocument.Parse(xmlString);

        // Get all the team nodes
        IEnumerable<XElement> nodeList = xmlDocument.Descendants("team");

        foreach (XElement node in nodeList)
        {
            // Create a new team in group standings
            TeamInGroupStanding team = new TeamInGroupStanding();

            // Get all the data from the xml document
            team.name = node.Element("name").Value;
            team.games = node.Element("games").Value;
            team.wins = node.Element("wins").Value;
            team.ties = node.Element("ties").Value;
            team.losses = node.Element("losses").Value;
            team.goals = node.Element("goals").Value;
            team.points = node.Element("points").Value;

            // Add the team to the list
            posts.Add(team);
        }
    }
    catch (Exception ex)
    {
        string exMessage = ex.Message;
    }

    // Return the list of posts
    return posts;

} // End of the GetTeamsFromXml method

Read all text as a string

The code below shows an example of reading all the text from a file to a string.

string path = "D:\\MyFolder\\Files\\myfile.json";

// Get the data
string data = System.IO.File.ReadAllText(path, Encoding.UTF8);

Read from JSON file

You can deserialize a JSON file to a model in C#. The code below shows how to read all text from a JSON file and deserialize it to a model.

// Document
AnnytabDoxTrade doc = null;
string file_path = "D:\\MyFolder\\Files\\myfile.json";

try
{
    // Get file data
    string file_data = System.IO.File.ReadAllText(file_path, Encoding.UTF8);

    // Make sure that there is file data
    if(string.IsNullOrEmpty(file_data) == true)
    {
        // Log the error
        this.logger.LogError($"File is empty: {file_path}.");
    }

    // Get the document
    doc = JsonConvert.DeserializeObject<AnnytabDoxTrade>(file_data);
}
catch(Exception ex)
{
    // Log the error
    this.logger.LogError(ex, $"Deserialize file: {file_path}", null);
}
public class AnnytabDoxTrade
{
    #region Variables

    public string id { get; set; }
    public string document_type { get; set; }
    public string payment_reference { get; set; }
    public string issue_date { get; set; }
    public string due_date { get; set; }
    public string delivery_date { get; set; }
    public string offer_expires_date { get; set; }
    public IDictionary<string, string> seller_references { get; set; }
    public IDictionary<string, string> buyer_references { get; set; }
    public string terms_of_delivery { get; set; }
    public string terms_of_payment { get; set; }
    public string mode_of_delivery { get; set; }
    public decimal? total_weight_kg { get; set; }
    public decimal? penalty_interest { get; set; }
    public string currency_code { get; set; }
    public string vat_country_code { get; set; }
    public string vat_state_code { get; set; }
    public string comment { get; set; }
    public PartyInformation seller_information { get; set; }
    public PartyInformation buyer_information { get; set; }
    public PartyInformation delivery_information { get; set; }
    public IList<PaymentOption> payment_options { get; set; }
    public IList<ProductRow> product_rows { get; set; }
    public IList<VatSpecification> vat_specification { get; set; }
    public decimal? subtotal { get; set; }
    public decimal? vat_total { get; set; }
    public decimal? rounding { get; set; }
    public decimal? total { get; set; }
    public decimal? paid_amount { get; set; }
    public decimal? balance_due { get; set; }

    #endregion

    #region Constructors

    public AnnytabDoxTrade()
    {
        // Set values for instance variables
        this.id = null;
        this.document_type = null;
        this.payment_reference = null;
        this.issue_date = null;
        this.due_date = null;
        this.delivery_date = null;
        this.offer_expires_date = null;
        this.seller_references = null;
        this.buyer_references = null;
        this.terms_of_delivery = null;
        this.terms_of_payment = null;
        this.mode_of_delivery = null;
        this.total_weight_kg = null;
        this.penalty_interest = null;
        this.currency_code = null;
        this.vat_country_code = null;
        this.vat_state_code = null;
        this.comment = null;
        this.seller_information = null;
        this.buyer_information = null;
        this.delivery_information = null;
        this.payment_options = null;
        this.product_rows = null;
        this.vat_specification = null;
        this.subtotal = null;
        this.vat_total = null;
        this.rounding = null;
        this.total = null;
        this.paid_amount = null;
        this.balance_due = null;

    } // End of the constructor

    #endregion

    #region Get methods

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);

    } // End of the ToString method

    #endregion

} // End of the class

Leave a Reply

Your email address will not be published. Required fields are marked *