我正在尝试.txt使用创建文件StreamWriter.我希望能够读取文本文件,然后自动将该文件的内容写入新.txt文件并将其存储到具有相同文件名的应用程序根目录.(希望这是有道理的.)
目前我无法找到解决方案让一切正常.请看我的代码.任何指导将不胜感激.
private void button1_Click(object sender, EventArgs e)
{
//read in a .txt file// this all works fine
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string filename = op.FileName;
// not working //
//create new .txt file contaning module notes
StreamWriter writer = new StreamWriter("..\\"op.FileName".txt" );
using (writer)
{
writer.Write(richTextBox1);
}
}
Run Code Online (Sandbox Code Playgroud)
Llo*_*oyd 10
这有几个问题,首先是:
StreamWriter writer = new StreamWriter("..\\"op.FileName".txt" );
Run Code Online (Sandbox Code Playgroud)
应该:
string filename = Path.GetFilename(op.FileName);
StreamWriter writer = new StreamWriter(".\\Notes\\" + filename);
Run Code Online (Sandbox Code Playgroud)
那么另一个问题是:
using (writer)
{
writer.Write(richTextBox1);
}
Run Code Online (Sandbox Code Playgroud)
尝试:
using (writer)
{
writer.Write(richTextBox1.Text);
}
Run Code Online (Sandbox Code Playgroud)
你基本上是在尝试编写一个RichTextBox实例,这当然不会像预期的那样工作string.
您可能还想重新考虑这个问题:
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
Run Code Online (Sandbox Code Playgroud)
if这里的构造只会考虑它之后的那条线,它将以下线条置于危险区域,就像你取消开放一样,它仍将运行.
所以把它们放在一起:
using (OpenFileDialog op = new OpenFileDialog())
{
op.Filter = "Text Files|*.txt"; // Nice to have a filter
if (op.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string filename = Path.GetFilename(op.FileName);
StreamWriter writer = new StreamWriter(".\\Notes\\" + filename);
using (writer)
{
writer.Write(richTextBox1.Text);
}
}
} // Clean up the OpenFileDialog instance
Run Code Online (Sandbox Code Playgroud)
这假定Notes目录存在.如果不是,你必须创建它.它还假定该目录位于工作目录中,该目录通常是运行可执行文件的目录.
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |