簡體   English   中英

讀取行並將其從外部文本文件 c# 中添加到列表中

[英]Read lines and add it to the list from an external text file c#

從外部文本文件讀取和解析每個部件行並將其添加到部件列表中的最佳方法是什么。 這是下面的代碼。

   List<Part> parts = new List<Part>();

    // Add parts to the list.
    parts.Add(new Part() {PartName = "crank arm", PartId = 1234});
    parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
    parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
    parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
    parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
    parts.Add(new Part() { PartName = "shift lever", PartId = 1634 });

這是我正在嘗試做的,但它不起作用。

  {
    var fileStream = new FileStream(@"~App_Data/file.text", FileMode.Open, FileAccess.Read);
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
      {
       string line;
       while ((line = streamReader.ReadLine()) != null) {

           parts.Add(new Part() { PartName = "", PartId= ""});

       }
  }

簡單的文本文件示例

new Part() {PartName = "crank arm", PartId = 1234};
new Part() { PartName = "chain ring", PartId = 1334 };
new Part() { PartName = "regular seat", PartId = 1434 };
new Part() { PartName = "banana seat", PartId = 1444 };
string lines = System.IO.File.ReadAllLines(MapPath(@"~/App_Data/file.text");
for(int i=0; i<lines.Lemgth; i++)
{
     Match m = Regex.Match(lines[i],"\{\s*PartName\s*=\s*\"([^\"]*)"\s*,\s*PartId\s*=\s*(\d+)\s*\}");
    if(m.Success) parts.Add(new Part(){PartName = m.Groups[1].Value, PartId = int.Parse(m.Groups[2].Value)});
}
        //references
        using System.IO;
        using System.Text.RegularExpressions;


        //code that goes in the method
        List<Part> parts = new List<Part>();
        foreach (string line in File.ReadAllLines(@"~App_Data/file.text"))
        {
            parts.Add(new Part()
            {
                PartName = line.Split('"')[1],
                PartId = Convert.ToInt32(Regex.Match(line, @"\d+").Value)
            });
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM