日期:2014-05-17  浏览次数:20937 次

请帮忙看一下这个FileStream的用法
第一段代码:e盘有个图片文件,用FileStream在d盘也整一个同样的图片
FileStream fs = new FileStream("e:\\6.jpg", FileMode.Open);  
byte[] temp = new byte[fs.Length];
fs.Read(temp, 0, (Int32)fs.Length);
fs = new FileStream(@"d:\1.jpg", FileMode.Create);
fs.Write(temp, 0, temp.Length);

第二段代码:e盘有个txt文件,用FileStream在d盘也整一个同样的txt文件
FileStream fs = new FileStream("e:\\6.txt", FileMode.Open);  
byte[] temp = new byte[fs.Length];
fs.Read(temp, 0, (Int32)fs.Length);
fs = new FileStream(@"d:\1.txt", FileMode.Create);
fs.Write(temp, 0, temp.Length);



问题:
上面两段代码,第一段代码能成功在d盘整一张同样的图片。第二段代码,在d盘的1.txt文件中,为什么没有写6.txt的内容,只是空的?
请问为什么?第一段代码能行,第二段代码不行

------解决方案--------------------
e:\\6.txt
这个文件存在么?

如果是拷贝文件,直接File.Copy就可以了。
------解决方案--------------------
要注意,有的时候,系统会隐藏文件的扩展名。

因此,你看上去是 6.txt,其实真实的文件名是 6.txt.txt
------解决方案--------------------
fs.Close(); 试试。。。
------解决方案--------------------
byte[] temp = new byte[fs.Length]; 改成//byte [] temp =new UTF8Encoding().GetBytes("e:\\6.txt"); 试试。
------解决方案--------------------
fs.Read(temp, 0, (Int32)fs.Length);改成fs.Read(temp, 0, (Int32)temp.Length)
------解决方案--------------------
flush 一下,并且,写完了要关闭,.close这些FileStream,养成良好习惯,否则会遇到这些文件没法删除、打开的异常
------解决方案--------------------
探讨
第一段代码:e盘有个图片文件,用FileStream在d盘也整一个同样的图片
FileStream fs = new FileStream("e:\\6.jpg", FileMode.Open);
byte[] temp = new byte[fs.Length];
fs.Read(temp, 0, (Int32)fs.Length);
fs = new FileStream(@"d:……

------解决方案--------------------
探讨

引用:
fs.Close(); 试试。。。
这个正确,可是,
为什么第一段代码不需要Close,也能画图片??