繁体   English   中英

如何从文件读取并保存到4个不同的变量(C#)?

[英]How to read from a file and save to 4 different variables (C#)?

我试图用我的SQL数据库信息创建一个设置文件,但是我目前遇到的问题是我似乎无法读取每一行并将其保存到其他变量中。

 private void readFile()
    { 
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\Settings.txt", true))

            while (sr.Peek() >= 0)
            {
                CurrentLine = sr.ReadLine();

            }
        }
    }

我不确定如何设置它,以便可以将每个不同的行写入4个变量。

任何帮助,将不胜感激!

我会使用一个数组来代替,您可以通过索引访问它:

string[] lines = File.ReadAllLines(@"C:\Users\Settings.txt");
string firstLine = lines[0];
// and so on, keep in mind that it could have less lines

具有四个变量的StreamReader方法更加麻烦:

using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\Settings.txt", true))
{ 
    string line;
    int currentLineNumber = 0;
    while ((line = sr.ReadLine()) != null)
    {
        switch (++currentLineNumber)
        {
            case 1: first = line; break;
            case 2: second = line; break;
            case 3: third = line; break;
            case 4: fourth = line; break;
        }
    }
}

当我需要将设置存储在文件中时,我创建了一个类来保存信息,例如

public class Settings{
   public string ConnectionString {get;set;}
   public string DatabaseName {get;set;}
   public DateTime Started {get;set;}
}

保存设置:

var settings = new Settings(){
   ConnectionString = "blah blah blah",
   DatabaseName = "blah blah blah",
   Started = DateTime.Now,
};
var json = JsonConvert.SerializeObject(settings);
File.WriteAllText(@"C:/Settings.txt", json);

正在加载设置:

var json = File.ReadAllText(@"C:/Settings.txt");
var settings = JsonConvert.DeserializeObject(json);

我发现这是可靠,灵活和稳定的。 这也意味着您不必担心在(例如)DateTime和String之间进行转换。 您也不必担心设置值的顺序。

(这使用Json.NET包。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM