我有下一个代码:
foreach (var te in lin)
{
if (te.Contains("license=") && te.Contains("license=false" ))
{
installertext = installertext.Replace("license=false", "license= " + "true");
}
else if (te.Contains("license="))
{
installertext = installertext.Replace("license=", "license=" + "true");
}
File.WriteAllText(installerfilename, installertext);
}
并且在text file
行中,license=
符号license=truetrue
出现license=true
。
我如何设置条件来验证行是否为空或使此代码只写break;
?我尝试添加license=
,但如果我执行此操作license=
仍然input:
{
"image": [
"content1",
"content2",
"content3"
],
"legal": [
"legal1",
"legal2",
"legal3"
],
"hyper": [
"hyper1",
"hyper2",
"hyper3"
]
}
答案 0 :(得分:1)
如果要替换
"license=false" => "license=true"
"license=" => "license=true"
附注:您期望不要遇到"license=true"
,是吗?您可以使用 Linq :
var target = lin
.Select(line => line.Contains("license=")
? line.Contains("license=false")
? line.Replace("license=false", "license=true")
: line.Replace("license=", "license=true")
: line);
File.WriteAllLines(installerfilename, target);
修改:如果您想要替换"license=sometext"
:
var target = lin
.Select(line => Regex.Replace(line, @"license=.*", "license=true"));
File.WriteAllLines(installerfilename, target);
答案 1 :(得分:0)
如果您逐行阅读文本文件,例如StreamReader
,那么您可以检查行是否为空或等于"license="
whitout为真。
using(StreamReader sr = new StreamReader("Filename"))
{
while (sr.EndOfStream)
{
string line = sr.ReadLine();
if(line.Trim().Length != 0 && line.Trim().Equals("license="))
{
//Do whatever you need to do
}
}
}