简体   繁体   English

C#从.txt文件中获取数据,并用分号分隔

[英]C# Getting Data from .txt File separated with Semicolons

By Example I have a .txt File with this content: 通过示例,我有一个.txt文件,其内容如下:

Hello;Test;StackOverflow;I live here
Hi;NoTest;StackOverflow;I don't live here

and so on.. 等等..

Now I would like to read the txtFile, but I don't want to read the "whole" line or everthing.. only to the next semicolon.. till the end of a Line.. 现在,我想读取txtFile,但我不想读取“整个”行或其他内容。仅读取下一个分号..直到一行的末尾。

one StringVariable for one Word in the txtFile but just for one line.. 一个StringVariable用于txtFile中的一个Word,但仅用于一行。

How could I achieve this? 我怎样才能做到这一点?

You can read text line by line like this: 您可以像这样逐行阅读文本:

var streamReader = new StreamReader(new FileStream("c:\\file.txt"));
var line = streamReader.ReadLine();

var values = line.Split(';');

and then read any value from line like this: 然后从这样的行读取任何值:

var value = values[2];

And if you want to iterate throught those values you can make it like this: 如果您想遍历这些值,可以这样:

var streamReader = new StreamReader(new FileStream("c:\\file.txt"));

while(!streamReader.EndOfStream)
{
    var line = streamReader.ReadLine()
    var values = line.Split(';');
    for(var i = 0; i < line.Length; i++)
        Console.WriteLine(values[i]); //example usage
}

streamReader.Dispose();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM