不错呦!smile@林凯西,确保“准备文件”中的几个文件都有安装,S...您好,看了您这篇帖子觉得很有帮助。但是有个问题想请...我的修改过了怎么还被恶意注册呢 @jjjjiiii 用PJ快9年了,主要是A...PJ3啊,貌似很少有人用PJ了,现在不是WP就是z...@332347365,我当时接入时错误码没有-10...楼主,ChkValue值应为-103是什么意思呢?...大哥 你最近能看到我发的信息,请跟我联系,我有个制...
FileStream复制文件注意事项
编辑:dnawo 日期:2009-08-11
使用FileStream读取文件时,为避免将大文件一次性全部读取到内存中,我们经常会声明一个byte[]做为临时存储空间,然后循环读取内容:
同理,在复制文件时我们也不希望将大文件一次性都读取到内存中,同样可以声明一个byte[]做为临时存储空间:
问题来了,当最后一次读取不满1024字节时,byte数组的剩余项都为0,这样在写入时将致使新文件比原文件占用更多的空间:

只需将代码稍加修改即可:
复制内容到剪贴板
程序代码

using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
同理,在复制文件时我们也不希望将大文件一次性都读取到内存中,同样可以声明一个byte[]做为临时存储空间:
复制内容到剪贴板
程序代码

public void CopyFile(string sourcepath, string destpath)
{
using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
{
using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
{
byte[] b = new byte[1024];
while (fs.Read(b, 0, b.Length) > 0)
{
fs2.Write(b, 0, b.Length);
}
}
}
}
{
using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
{
using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
{
byte[] b = new byte[1024];
while (fs.Read(b, 0, b.Length) > 0)
{
fs2.Write(b, 0, b.Length);
}
}
}
}
问题来了,当最后一次读取不满1024字节时,byte数组的剩余项都为0,这样在写入时将致使新文件比原文件占用更多的空间:

只需将代码稍加修改即可:
复制内容到剪贴板
程序代码

public void CopyFile(string sourcepath, string destpath)
{
using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
{
using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
{
byte[] b = new byte[1024];
int l = 0;
while ((l = fs.Read(b, 0, b.Length)) > 0)
{
fs2.Write(b, 0, l);
}
}
}
}
{
using (FileStream fs = new FileStream(sourcepath, FileMode.Open, FileAccess.Read))
{
using (FileStream fs2 = new FileStream(destpath, FileMode.Create, FileAccess.Write))
{
byte[] b = new byte[1024];
int l = 0;
while ((l = fs.Read(b, 0, b.Length)) > 0)
{
fs2.Write(b, 0, l);
}
}
}
}
评论: 0 | 引用: 0 | 查看次数: 4763
发表评论
请登录后再发表评论!