C#在文本文件的某一行读取

时间:2017-03-29 09:28:52

标签: c#

嗨我需要从一个结构如下的文本文件中读取:

DataSource = WS****\SQLEXPRESS  
DataBase = *********  
UserName = sa  
PassWord = ****  

星星是关于数据库的信息

但是我只想在信息开始的'='之后开始从1个空格开始阅读这是我的代码

string fileLocation = Environment.CurrentDirectory + "\\SQLConfigSettings.txt";

if (!File.Exists(fileLocation))
{
    using (File.Create(fileLocation)) { }
}
using (FileStream fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        fs.Seek(13, SeekOrigin.Begin);
        dataSource = sr.ReadLine();

        fs.Seek(11, SeekOrigin.Begin);
        dataBaseName = sr.ReadLine();
        MessageBox.Show(dataBaseName);

        fs.Seek(11, SeekOrigin.Begin);
        userName = sr.ReadLine();

        fs.Seek(11, SeekOrigin.Begin);
        passWord = sr.ReadLine();
    }
}

我的想法是,这将寻找第一行读取,向下移动一行,再次搜索,读取行等。第一行有效,但下一行只显示整个行。

谢谢!

1 个答案:

答案 0 :(得分:0)

List<string> lines = File.ReadLines(path, Encoding.Default).ToList();

string dataSource = lines[0].Replace("DataSource = ", "");
string database = lines[1].Replace("DataBase = ", "");
string userName = lines[2].Replace("UserName = ", "");
string password = lines[3].Replace("PassWord = ", "");