C# 文件流错误:myStream.Read(50分)

  • 主题发起人 主题发起人 VGA
  • 开始时间 开始时间
V

VGA

Unregistered / Unconfirmed
GUEST, unregistred user!
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream, youStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c://" ;
openFileDialog1.Title = "打开源文件";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
myStream = File.OpenRead(openFileDialog1.FileName);
}
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = "c://";
saveFileDialog1.Title = "另存文件为";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
youStream = File.OpenWrite(saveFileDialog1.FileName);
}
byte [] buf = new byte[512];
int intRead = 0;
intRead = myStream.Read(buf, 0, buf.Length);
// 此句出错
youStream.Write(buf, 0, intRead);
// 此句出错
myStream.Close();
youStream.Close();
}
应该怎样写? (初学C#, 见笑)
 
你的错误估计是没有申明,要知道C#中局部变量必须申明的。
问题是按照你的程序逻辑,只能读到512K的位置的,保存不了整个文件,修改的代码如下,自己去看了,
另外有没有发觉你的OpenFileDialoge和SaveFileDialoge是如此的相似,考虑没考虑如何取出共通呢 ?那就是你的事了
Stream myStream = null;
Stream youStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c://" ;
openFileDialog1.Title = "打开源文件";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
myStream = File.OpenRead(openFileDialog1.FileName);
}
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = "c://";
saveFileDialog1.Title = "另存文件为";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
youStream = File.OpenWrite(saveFileDialog1.FileName);
}
byte [] buf = new byte[512];
int intRead = 0;
try
{
while ( ( intRead = myStream.Read(buf, 0, buf.Length) ) > 0 ) // 此句出错
{
youStream.Write(buf, 0, intRead);
// 此句出错
}
}
catch(Exception)
{}
finally
{
myStream.Close();
youStream.Close();
}
 
谢过 网事如风 大侠
 
接受答案了.
 
后退
顶部