[英].Reading and writing to a file from the same textbox
我有一个Windows窗体,可以从文件中读取字符串,并在按下按钮时将其全部显示在文本框中。
private void buttonTxt_Click(object sender, EventArgs e)
{
string[] Test = File.ReadAllLines("C:\\testfile.txt");
for (int i = 0; i < testfile.Length; i++)
{
TextBox.Text += testfile[i];
}
}
我想做两个单选按钮。 因此,第一个按钮使我的程序按我描述的方式工作(默认情况下),第二个单选按钮使它反之亦然- 这样我可以自己在文本框中编写内容,当我按下按钮时,它会在同一行中写一行新行文件 。 有办法吗?
只需在此事件处理程序中添加if
语句,即可实现发送和接收数据。 完成。 样品原理:
private const string FilePath = @"C:\testfile.txt";
private void buttonTxt_Click(object sender, EventArgs e)
{
if (radioReadMode.Checked) // check which radio button is selected
{ // read mode
string[] Test = File.ReadAllLines(FilePath);
for (int i = 0; i < testfile.Length; i++)
TextBox.Text += testfile[i];
}
else
{ // write mode
File.WriteAllText(FilePath, TextBox.Text);
}
}
我相信这就是您想要的。 如果选中单选按钮1,则如果文件存在,它将读取该文件并将其放入表单的文本框中。 如果切换到单选按钮2,则可以在文本框中键入内容,然后在按下按钮时将其附加到文件中。
public partial class Form1 : Form
{
System.IO.StreamReader sr;
System.IO.StreamWriter sw;
public Form1()
{
InitializeComponent();
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sr = new System.IO.StreamReader("C:\\testfile.txt");
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + "\r\n";
}
}
finally
{
sr.Close();
sr.Dispose();
}
}
}
if (radioButton2.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sw = new System.IO.StreamWriter("C:\\testfile.txt", true);
string result = textBox1.Text;
string[] lststr = result.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lststr)
{
sw.WriteLine(s);
}
}
finally
{
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = false;
}
}
是的,有办法。 只需在表单中添加另一个按钮,然后在内部从文本框中读取文本即可:
var textBoxContent = TextBox.Text;
并以这种方式将其保存到您的文件中
File.WriteAllText("C:\\testfile.txt", textBoxContent);
注意:我建议将文件路径放入变量中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.