![](/img/trans.png)
[英]how to read repeated chunk of data from a text file in a different variables
[英]How to read different types of data from text file?
我需要從文件中讀取文本數據,其中每行中都有不同類型的數據。 因此,我創建了一個名為subject的大類。 我的數據如下所示:
Subject name M1 M2 M3 M4
Subject1 5 7 8 3
Old Subject 1 2 5 9
主要的問題是,例如是否可以讀取第1行中的所有數據並將其分配給適當的字段,例如SubjName = Subject1,M1 = 5,M2 = 7,M3 = 8,依此類推,而無需使用子字符串? (類似於流>> Subject.SubjName;在C ++中,流>> Subject.M1 = 5等等)。
這是我的代碼。
internal void Read()
{
TextReader tr = new StreamReader("Data.txt");
string line;
while ((line = tr.ReadLine()) != null) //read till end of line
{
tr.ReadLine(); //Skips the first line
}
提前致謝
編輯:為澄清起見,我希望字段是定界的。
類似於此問題中的解決方案可能會有所幫助,但顯然使用制表符(\\ t)
from line in File.ReadAllLines(fileName).Skip(1)
let columns = line.Split(',')
select new
{
Plant = columns[0],
Material = int.Parse(columns[1]),
Density = float.Parse(columns[2]),
StorageLocation = int.Parse(columns[3])
}
從您的問題尚不清楚記錄如何存儲在文件中-字段是定界還是定長。
無論如何-您可以使用TextFieldParser
類,該類:
提供用於解析結構化文本文件的方法和屬性。
它位於Microsoft.VisualBasic.dll
程序集中的Microsoft.VisualBasic.FileIO
命名空間中。
拆分和字典以及您在此處選擇的兩種方法。 您讀入一行,將其分隔為空白,然后將其另存為字典中的名稱/對象對。
將下面的代碼放入* .cs文件,然后進行構建並作為演示運行:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
namespace stringsAsObjects
{
class stringObject
{
public static int Main(string[] args)
{
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("Data.txt");
string nameLine = file.ReadLine();
string valueLine = file.ReadLine();
file.Close();
string[] varNames = nameLine.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
string[] varValues = valueLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, object> map = new Dictionary<string, object>();
for(int i = 0; i<varNames.Length; i++)
{
try
{
map[varNames[i]] = varValues[i];
}
catch (Exception ex)
{
map[varNames[i]] = null;
}
}
foreach (object de in map)
{
System.Console.WriteLine(de);
}
Console.ReadKey();
return 0;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.