需求:
1、读取Config.ini文件
2、将里面的Address/Port=0xfed30328 这一行的0xfed30328取出来
这是Config.ini文件的具体内容:
说明:
1、首先ini 文件是Initialization File的缩写,即初始化文件,是windows的系统配置文件所采用的存储格式。
2、由于涉及到具体取某一行的具体内容,所以这里我们要用到String的Split方法
代码:
using System;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Text;
namespace TestRw0730
{
public class Program
{
public static String getAddress(String path)
{
String result = null;
FileStream fs = null;
StreamReader textReader = null;
try
{
string content = string.Empty;
fs = new FileStream(path, FileMode.Open);
textReader = new StreamReader(fs);
while (null != (content = textReader.ReadLine()))
{
content = content.Trim().ToString();
string[] sArray = content.Split(new char[] { '=' });
if (sArray[0].Equals(@"Address/Port"))
{
result = sArray[1].Trim();
break;
}
}
}
catch
{
Console.Write("错误");
}
finally
{
if (textReader != null)
{
textReader.Close();
}
if (fs != null)
{
fs.Close();
}
}
return result;
}
static void Main(string[] args)
{
String path = @"C:\Users\123\Desktop\RWRead\Config.ini";
String add = getAddress(path);
Console.WriteLine(add);
Console.ReadLine();
}
}
解释:
1、我们的split方法是将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
2、我们用sArray 这个数组来接收,sArray[0]就是Address/Port,sArray[1]就是0xfed30328,所以我们取出sArray[1]就是我们要的结果
string[] sArray = content.Split(new char[] { '=' });
if (sArray[0].Equals(@"Address/Port"))
{
result = sArray[1].Trim();
break;
}