如何从文本文件中获取值并在文本框中设置它们
本文关键字:文本 设置 获取 文件 | 更新日期: 2023-09-27 17:52:50
问题来了:我有两个类。表单1创建了一个.txt- file并在其中设置了两个值(string)。现在我想通过按下按钮(bdireckt)来获得这两个字符串,并在表单2的文本框中设置每个字符串。
表格1(据我所知应该是正确的,但如果我错了,请告诉我):
public void Txfw()
{
string txBetrag = gBetrag.Text;
string txMonate = gMonate.Text;
string[] vars = new string[] { txBetrag, txMonate };
using (StreamWriter sw = new StreamWriter(@"C:'Users'p2'Desktop'variablen.txt"))
{
foreach (string s in vars)
{
sw.WriteLine(s);
}
}
}
表格二(不知道如何进行):
private void bDirekt_Click(object sender, RoutedEventArgs e)
{
using (StreamReader sr = new StreamReader("variables.txt")) ;
string line = "";
while ((line = sr.ReadLine()) != null)
{
monate2.Text =
}
}
我非常感谢你的帮助。
试试这个
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(@"C:'Users'p2'Desktop'variablen.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
sb.Append((line);
}
}
monate2.Text = sb.Tostring();
UPDATE:要将第一行与其余文本分开,您可以尝试这样做。总有更好的方法来实现这一点。
StringBuilder sb = new StringBuilder();
string headerLine = string.Empty;
int currentLine = 0;
using (StreamReader sr = new StreamReader(@"C:'Users'p2'Desktop'variablen.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
currentLine++; //increment to keep track of current line number.
if(currentLine == 1)
{
headerLine = line;
continue; //skips rest of the processing and goes to next line in while loop
}
sb.Append((line);
}
}
header.Text = headerLine;
monate2.Text = sb.ToString();