Denna artikel visar några alternativ för att läsa in text från en fil med C# i ASP.NET Core. Du kanske vill läsa text från en fil för att importera data eller för att få inmatning till ditt program.
Inläsning från CSV-fil
En CSV-fil är en textfil där data på varje rad skiljs åt av kommatecken (,), andra tecken kan användas som separatorer. En CSV-fil kan exporteras från Excel eller Open Office Calc till exempel.
List<string[]> values = new List<string[]>();
using (StreamReader reader = new StreamReader("D:\\MyFolder\\Files\\case.txt"))
{
while(!reader.EndOfStream)
{
values.Add(reader.ReadLine().Split(','));
}
}
Inläsning från XML-fil
XML-filer används ofta i olika standarder och liknar HTML. Koden nedan visar ett exempel på inläsning av lag från en XML-fil som representerar en tabell.
<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
Läs all text som en sträng
Koden nedan visar ett exempel på inläsning av all text från en fil till en sträng.
string path = "D:\\MyFolder\\Files\\myfile.json";
// Get the data
string data = System.IO.File.ReadAllText(path, Encoding.UTF8);
Inläsning från JSON-fil
Du kan deserialisera en JSON-fil till en modell i C#. Koden nedan visar hur man kan läsa in all text från en JSON-fil och deserialisera strängen till en modell.
// 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