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.

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

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.

  1. <standings>
  2. <team>
  3. <name>Malmö FF</name>
  4. <games>7</games>
  5. <wins>4</wins>
  6. <ties>2</ties>
  7. <losses>1</losses>
  8. <goals>12-7 (5)</goals>
  9. <points>14</points>
  10. </team>
  11. <team>
  12. <name>IFK Göteborg</name>
  13. <games>7</games>
  14. <wins>4</wins>
  15. <ties>1</ties>
  16. <losses>2</losses>
  17. <goals>16-9 (7)</goals>
  18. <points>13</points>
  19. </team>
  20. <team>
  21. <name>BK Häcken</name>
  22. <games>7</games>
  23. <wins>4</wins>
  24. <ties>1</ties>
  25. <losses>2</losses>
  26. <goals>10-4 (6)</goals>
  27. <points>13</points>
  28. </team>
  29. </standings>
  1. public class TeamInGroupStanding
  2. {
  3. #region Variables
  4. public string name { get; set; }
  5. public string games { get; set; }
  6. public string wins { get; set; }
  7. public string ties { get; set; }
  8. public string losses { get; set; }
  9. public string goals { get; set; }
  10. public string points { get; set; }
  11. #endregion
  12. #region Constructors
  13. public TeamInGroupStanding()
  14. {
  15. // Set values for instance variables
  16. this.name = "";
  17. this.games = "";
  18. this.wins = "";
  19. this.ties = "";
  20. this.losses = "";
  21. this.goals = "";
  22. this.points = "";
  23. } // End of the constructor
  24. #endregion
  25. } // End of the class
  1. public IList<TeamInGroupStanding> GetTeamsFromXml(string xmlString)
  2. {
  3. // Create the list to return
  4. IList<TeamInGroupStanding> posts = new List<TeamInGroupStanding>(12);
  5. try
  6. {
  7. // Create the xml document
  8. XDocument xmlDocument = XDocument.Parse(xmlString);
  9. // Get all the team nodes
  10. IEnumerable<XElement> nodeList = xmlDocument.Descendants("team");
  11. foreach (XElement node in nodeList)
  12. {
  13. // Create a new team in group standings
  14. TeamInGroupStanding team = new TeamInGroupStanding();
  15. // Get all the data from the xml document
  16. team.name = node.Element("name").Value;
  17. team.games = node.Element("games").Value;
  18. team.wins = node.Element("wins").Value;
  19. team.ties = node.Element("ties").Value;
  20. team.losses = node.Element("losses").Value;
  21. team.goals = node.Element("goals").Value;
  22. team.points = node.Element("points").Value;
  23. // Add the team to the list
  24. posts.Add(team);
  25. }
  26. }
  27. catch (Exception ex)
  28. {
  29. string exMessage = ex.Message;
  30. }
  31. // Return the list of posts
  32. return posts;
  33. } // 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.

  1. string path = "D:\\MyFolder\\Files\\myfile.json";
  2. // Get the data
  3. 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.

  1. // Document
  2. AnnytabDoxTrade doc = null;
  3. string file_path = "D:\\MyFolder\\Files\\myfile.json";
  4. try
  5. {
  6. // Get file data
  7. string file_data = System.IO.File.ReadAllText(file_path, Encoding.UTF8);
  8. // Make sure that there is file data
  9. if(string.IsNullOrEmpty(file_data) == true)
  10. {
  11. // Log the error
  12. this.logger.LogError($"File is empty: {file_path}.");
  13. }
  14. // Get the document
  15. doc = JsonConvert.DeserializeObject<AnnytabDoxTrade>(file_data);
  16. }
  17. catch(Exception ex)
  18. {
  19. // Log the error
  20. this.logger.LogError(ex, $"Deserialize file: {file_path}", null);
  21. }
  1. public class AnnytabDoxTrade
  2. {
  3. #region Variables
  4. public string id { get; set; }
  5. public string document_type { get; set; }
  6. public string payment_reference { get; set; }
  7. public string issue_date { get; set; }
  8. public string due_date { get; set; }
  9. public string delivery_date { get; set; }
  10. public string offer_expires_date { get; set; }
  11. public IDictionary<string, string> seller_references { get; set; }
  12. public IDictionary<string, string> buyer_references { get; set; }
  13. public string terms_of_delivery { get; set; }
  14. public string terms_of_payment { get; set; }
  15. public string mode_of_delivery { get; set; }
  16. public decimal? total_weight_kg { get; set; }
  17. public decimal? penalty_interest { get; set; }
  18. public string currency_code { get; set; }
  19. public string vat_country_code { get; set; }
  20. public string vat_state_code { get; set; }
  21. public string comment { get; set; }
  22. public PartyInformation seller_information { get; set; }
  23. public PartyInformation buyer_information { get; set; }
  24. public PartyInformation delivery_information { get; set; }
  25. public IList<PaymentOption> payment_options { get; set; }
  26. public IList<ProductRow> product_rows { get; set; }
  27. public IList<VatSpecification> vat_specification { get; set; }
  28. public decimal? subtotal { get; set; }
  29. public decimal? vat_total { get; set; }
  30. public decimal? rounding { get; set; }
  31. public decimal? total { get; set; }
  32. public decimal? paid_amount { get; set; }
  33. public decimal? balance_due { get; set; }
  34. #endregion
  35. #region Constructors
  36. public AnnytabDoxTrade()
  37. {
  38. // Set values for instance variables
  39. this.id = null;
  40. this.document_type = null;
  41. this.payment_reference = null;
  42. this.issue_date = null;
  43. this.due_date = null;
  44. this.delivery_date = null;
  45. this.offer_expires_date = null;
  46. this.seller_references = null;
  47. this.buyer_references = null;
  48. this.terms_of_delivery = null;
  49. this.terms_of_payment = null;
  50. this.mode_of_delivery = null;
  51. this.total_weight_kg = null;
  52. this.penalty_interest = null;
  53. this.currency_code = null;
  54. this.vat_country_code = null;
  55. this.vat_state_code = null;
  56. this.comment = null;
  57. this.seller_information = null;
  58. this.buyer_information = null;
  59. this.delivery_information = null;
  60. this.payment_options = null;
  61. this.product_rows = null;
  62. this.vat_specification = null;
  63. this.subtotal = null;
  64. this.vat_total = null;
  65. this.rounding = null;
  66. this.total = null;
  67. this.paid_amount = null;
  68. this.balance_due = null;
  69. } // End of the constructor
  70. #endregion
  71. #region Get methods
  72. public override string ToString()
  73. {
  74. return JsonConvert.SerializeObject(this);
  75. } // End of the ToString method
  76. #endregion
  77. } // End of the class

Leave a Reply

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