如何将文本框的值指定为文件名
问题描述:
我正在写一个小文件应用程序。
我有两个文本框,textBox1
适用于输入文件的注释,这将创建一个.txt文件。
第二个是从文件中读取。我需要将 TextBox1
的值赋给变量( filename
),以便它动态命名文本文件。我可能会以错误的方式解决这个问题。任何帮助将不胜感激。下面是代码。等待回复。
I writing a small file application.
I have two text boxes, "textBox1"
is for entering a note for a file, this creates a .txt file.
Second one is to read from the file. I need to assign the value of TextBox1
to a variable(filename
) so that it will name the text file dynamically. I may be going about this the wrong way. Any help will be greatly appreciated. Below is the code. Waiting for some reply.
private void btnWrite_Click(object sender, EventArgs e)
{
String filename = textbox1.Text;
// write a line of text to the file
TextWriter te = new StreamWriter(???);
// close the stream
te.Close();
}
private void btnRead_Click(object sender, EventArgs e)
{
// create reader & open file
TextReader tr = new StreamReader(???);
// read a line of text
txtRead.Text = tr.ReadLine();
// close the stream
tr.Close();
}
答
你可以试试
You can try
private void btnWrite_Click(object sender, EventArgs e)
{
//Application.StartupPath gives the path of the executable file of the application.
String filename = string.Format("{0}\{1}.txt",Application.StartupPath, textbox1.Text);
string textToWrite = "Assign the text to write here";
File.WriteAllText(filename, textToWrite);
//You can use
//File.AppendAllText(filename, textToWrite);
//to append the text to the end of an existing file
}
private void btnRead_Click(object sender, EventArgs e)
{
String filename = String filename = string.Format("{0}\{1}.txt",
Application.StartupPath, textbox1.Text);
string textFromFile = File.ReadAllText(filename);
}
你面临什么问题?你收到任何错误吗?
如果你想知道如何使用StreamReader和StreamWriter进行读写,请参考 this [ ^ ]
----- ------更新--------------------
Chech 这个 [ ^ ]
What problem are you facing? Are you getting any error?
If you want to know how to read and write using StreamReader and StreamWriter then refer this[^]
-----------Updated--------------------
Chech this[^]
您的代码被重构为:
Your code is refactored as:
private void btnWrite_Click(object sender, EventArgs e)
{
String filename = textbox1.Text;
// write a line of text to the file
TextWriter te = new StreamWriter(???);
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write("content to be written");
// close the stream
writer.Close();
}
}
private void btnRead_Click(object sender, EventArgs e)
{
// create reader & open file
TextReader tr = new StreamReader(???);
using (StreamReader reader = new StreamReader(filename))
{
// read a line of text
txtRead.Text = reader.ReadLine();
// close the stream
reader.Close();
}
}