C#:读取TXT文件数据 [英] C#: Read data from txt file
问题描述
我有一个.EDF(文本)文件。该文件的内容如下:
I have an .EDF (text) file. The file's contents are as follows:
ConfigFile.Sample, Software v0.32, CP Version 0.32
[123_Float][2]
[127_Number][0]
[039_Code][70]
我wnat阅读这些内容,并分析它们是这样的:
I wnat to read these items and parse them like this:
123_Float - 2
127_Number - 0
039_Code - 70
我怎样才能做到这一点使用C#
How can I do this using C#?
推荐答案
那么,你可能会用的 File.ReadAllLines()
方法。然后,遍历该文件中的行,检查,看看它们是否匹配的模式。如果他们这样做,提取必要的文本,做任何你想做的事情。
Well, you might start with the File.ReadAllLines()
method. Then, iterate through the lines in that file, checking to see if they match a pattern. If they do, extract the necessary text and do whatever you want with it.
下面是你想要的格式线假定一个例子 [(场1)] [(场2)]
:
Here's an example that assumes you want lines in the format [(field 1)][(field 2)]
:
// Or wherever your file is located
string path = @"C:\MyFile.edf";
// Pattern to check each line
Regex pattern = new Regex(@"\[([^\]]*?)\]");
// Read in lines
string[] lines = File.ReadAllLines(path);
// Iterate through lines
foreach (string line in lines)
{
// Check if line matches your format here
var matches = pattern.Matches(line);
if (matches.Count == 2)
{
string value1 = matches[0].Groups[1].Value;
string value2 = matches[1].Groups[1].Value;
Console.WriteLine(string.Format("{0} - {1}", value1, value2));
}
}
这把它们输出到控制台窗口,但你可以明明做任何你想要与值1
和值2
(它们写入另一个文件,将它们存储在数据结构等)。
This outputs them to the console window, but you could obviously do whatever you want with value1
and value2
(write them to another file, store them in a data structure, etc).
另外,请注意,正则表达式是不是我的强项 - 可能有一个更优雅的方式来检查线路的模式匹配:)
Also, please note that regular expressions are not my strong point -- there's probably a much more elegant way to check if a line matches your pattern :)
如果您想了解更多信息,请查看MSDN的上的从文本中读取数据文件作为一个起点。
If you want more info, check out MSDN's article on reading data from a text file as a starting point.
这篇关于C#:读取TXT文件数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!