c#???????

sun112x 2008-12-27 12:02:46
请问一下,在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)不相符,原文本文件中被删除了一不分内容,如果直接指定地址则不会出现上述情况,为什么?
还有个问题,使用正则式也会自己删除文件内容,为什么?
...全文
76 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
sun112x 2008-12-31
  • 打赏
  • 举报
回复
谢谢!
net5i 2008-12-27
  • 打赏
  • 举报
回复
搂主改成下面的,
string readpath = open.FileName;
string writepath = System.IO.Path.GetDirectoryName(readpath) + @"\修改.txt";

因为你的这样的路径:string writepath = @"修改.txt";
是不定的,是不断变化的,是OpenFileDialog打开的文件所在的目录
flyjimi 2008-12-27
  • 打赏
  • 举报
回复
write.Write(a);
write.Flush();
write.Close();

缓冲中有一些数据还没有写入文件,程序就退出了。
gomoku 2008-12-27
  • 打赏
  • 举报
回复

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);
}
优途科技 2008-12-27
  • 打赏
  • 举报
回复
顶一下。
wangping_li 2008-12-27
  • 打赏
  • 举报
回复
我认为是StreamWriter 没有关闭的问题,就像gomoku说的,很可能造成数据丢失
把它放到using块中执行,完了后会自动释放
using (StreamWriter write = new StreamWriter(writepath))
{
//执行
}

111,130

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧