C#如何读取ini文件,并读取某一行的某个指定内容(使用split方法)

需求:

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;
                    }
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值