我有一个文本文件installer.ini
,其中有一行是:fileExecutable=D:\location
。我想在获取文本后将=
其放入变量中。之后,我要使用该变量而不是D:\location
代码。
foreach (var txt in lin)
{
if (txt.Contains("fileExecutable="))
{
var ExeFile = txt.Split('=')[1];
}
}
// The installer itself
process.StartInfo.FileName = @"D:\location";
process.StartInfo.Arguments = @"-if C:\temp\installer.ini";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit();
}
我尝试将变量ExeFile
放在文本文件中,fileExecutable=
然后在此行中使用该变量:process.StartInfo.FileName = @"D:\location";
该变量ExeFile
在foreach
循环内声明,因此在循环后不可用。如果将其移出循环,则可以在循环后使用它。
var ExeFile = String.Empty;
foreach (var txt in lin)
{
if (txt.Contains("fileExecutable="))
{
ExeFile = txt.Split('=')[1];
}
}
if (!String.IsNullOrEmpty(ExeFile))
{
// The installer itself
process.StartInfo.FileName = ExeFile;
process.StartInfo.Arguments = @"-if C:\temp\installer.ini";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit();
}
编辑替代
您可以在整个INI文件上使用regelar表达式来跳过所有行的循环,如下所示:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
// dummy ini for testing.
var ini = "test\nfileExecutable=D:\\location\ntest";
var regex = new Regex("^fileExecutable=(.+)$", RegexOptions.Multiline);
var location = regex.Match(ini).Groups[1];
Console.WriteLine(location);
}
}
编辑另一种选择
编辑问题标题后,您可能还希望从ini阅读其他设置。如果是这样,请考虑使用INI读取器,如下所述:读取/写入INI文件
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句