如何从特定位置读取文本文件,例如我有文本文件
pathA = sometexthere$
pathB = sometexthere$
pathC = sometexthere$
TimerTC = sometexthere$
我想阅读" ="之间的所有内容。和" $"
使用以下方法逐行阅读:
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("config.cfg");
while((line = file.ReadLine()) != null)
{
if (counter == 1)
{
label1.Text=line;
counter++;
}
else if (counter == 2)
{
label2.Text=line;
counter++;
}
}
答案 0 :(得分:3)
File.ReadLines("path")
.Select(line => new string(line
.SkipWhile(c => c != '=')
.Skip(1)
.TakeWhile(c => c != '$').ToArray())).ToList();
答案 1 :(得分:1)
解决方案1:
int index;
List<string> listLines = new List<string>();
foreach (var line in File.ReadLines("C:\\Data.txt"))
{
index = line.LastIndexOf('=');
listLines.Add(line.Substring(index + 1, (line.Length - index) -
((line.Length) - line.LastIndexOf('$')+1)));
}
<强>溶液2:强>
您可以使用分隔符=
拆分每一行,然后提取以=
开头的单词$
string str;
List<string> listLines = new List<string>();
foreach (var line in File.ReadLines("C:\\Data.txt"))
{
str = line.Split('=')[1].Trim();
listLines.Add(str.Substring(0, str.Length -
(str.Length - str.LastIndexOf('$'))));
}
解决方案3:
List<string> listLines = new List<string>();
foreach (var line in File.ReadLines("C:\\Data.txt"))
{
var str = line.Split(new char[] { '=', '$'},
StringSplitOptions.RemoveEmptyEntries);
listLines.Add(str[1].Trim());
}
答案 2 :(得分:1)
您也可以使用正则表达式(although, now you have two problems)执行此操作:
var regex = new Regex(
@"^ # beginning of the line
(?<key>.*?) # part before the equals sign
\s*=\s* # `=` with optional whitespace
(?<value>.*) # part after the equals sign
\$ # `$`
$ # end of the line",
RegexOptions.Multiline |
RegexOptions.IgnorePatternWhitespace |
RegexOptions.Compiled);
或者,一个班轮:
var regex = new Regex(@"^(?<key>.*?)\s*=\s*(?<value>.*)\$$");
然后选择匹配到键值对:
var keyValuePairs = File
.ReadLines("config.cfg")
.Select(line => regex.Match(line))
.Where(match => match.Success)
.Select(match => new
{
Key = match.Groups["key"].Value,
Value = match.Groups["value"].Value
})
.ToList();