流阅读器第二行视觉工作室c#

时间:2015-08-28 11:36:58

标签: c# streamreader readline

我正在使用此方法将我的连接句子保存到文本文件中:

MemoryStream ms = new MemoryStream();

byte[] memData = Encoding.UTF8.GetBytes("Data Source=" + textBox1.Text + ";" + Environment.NewLine + "Initial Catalog=" + textBox2.Text + ";" + Environment.NewLine + "User ID=" + textBox3.Text + ";" + Environment.NewLine + "password=" + textBox4.Text + ";");

ms.Write(memData, 0, memData.Length);
FileStream strm = new FileStream(@"C:\Users\Çağatay\Desktop\test.txt", FileMode.Create, FileAccess.Write);
ms.WriteTo(strm);
ms.Close();
strm.Close();
MessageBox.Show("Connection Saved");

是否有使用streamreader将行重新加载到文本框的方法?

我搜索并发现了这个:

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Çağatay\Desktop\test.txt");
while ((line = file.ReadLine()) != null)
{
    MessageBox.Show(line);
    counter++;
}

file.Close();

但我需要这样的东西:

textbox1.text=streamreader.readline[0]
textbox2.text=streamreader.readline[1]

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

你有什么理由不加载整个文件吗?

string[] lines = File.ReadAllLines(@"C:\Users\Çağatay\Desktop\test.txt");

同样,您的第一段代码将更加简单:

File.WriteAllLines(
    @"C:\Users\Çağatay\Desktop\test.txt",
    new[]
    {
        "Data Source=" + textBox1.Text + ";",
        "Initial Catalog=" + textBox2.Text + ";", 
        "User ID=" + textBox3.Text + ";",
        "password=" + textBox4.Text + ";"
    });

或使用C#6:

File.WriteAllLines(
    @"C:\Users\Çağatay\Desktop\test.txt",
    new[]
    {
        $"Data Source={textBox1.Text};",
        $"Initial Catalog={textBox2.Text};",
        $"User ID={textBox3.Text};",
        $"password={textBox4.Text};"
    });