请问一下,在winform中有一个openfiledialogue组件,想在button事件中激发该事件添加代码如下
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.InitialDirectory == null)
open.ShowDialog();
open.Filter = "所有文档文件(*.txt)|*.txt";
open.Multiselect = false;
if (open.ShowDialog(this) == DialogResult.Cancel)
return;
string readpath = open.FileName;
string writepath = @"修改.txt";
StreamReader read = new StreamReader(readpath);
string a = read.ReadToEnd();
StreamWriter write = new StreamWriter(writepath);
write.Write(a);
MessageBox.Show("写完!");
Application.Exit(); 修改.txt的内容和原文本文件(也是txt)不相符,原文本文件中被删除了一不分内容,如果直接指定地址则不会出现上述情况,为什么?
还有个问题,使用正则式也会自己删除文件内容,为什么?
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.InitialDirectory == null)
open.ShowDialog();
open.Filter = "所有文档文件(*.txt)|*.txt";
open.Multiselect = false;
if (open.ShowDialog(this) == DialogResult.Cancel)
return;
string readpath = open.FileName;
string writepath = @"修改.txt";
StreamReader read = new StreamReader(readpath);
string a = read.ReadToEnd();
StreamWriter write = new StreamWriter(writepath);
write.Write(a);
MessageBox.Show("写完!");
Application.Exit(); 修改.txt的内容和原文本文件(也是txt)不相符,原文本文件中被删除了一不分内容,如果直接指定地址则不会出现上述情况,为什么?
还有个问题,使用正则式也会自己删除文件内容,为什么?
string readpath = open.FileName;
string writepath = @"修改.txt";string a = File.ReadAllText(readpath);// StreamWriter不关闭可能会丢失数据,建议用using模式。
// 该模式会自动调用Dispose,导致StreamWriter得到关闭。
using (StreamWriter write = new StreamWriter(writepath))
{
write.Write(a);
}
write.Flush();
write.Close();缓冲中有一些数据还没有写入文件,程序就退出了。
string readpath = open.FileName;
string writepath = System.IO.Path.GetDirectoryName(readpath) + @"\修改.txt"; 因为你的这样的路径:string writepath = @"修改.txt";
是不定的,是不断变化的,是OpenFileDialog打开的文件所在的目录
把它放到using块中执行,完了后会自动释放
using (StreamWriter write = new StreamWriter(writepath))
{
//执行
}