C# FileStream 对象的Seek()方法

FileStream 可以随机读写文件 使用 Seek 方法

Seek()  ----------有两个参数 第一参数规定文件指针以字节为单位移动的距离。第二个参数规定开始计算的位置

用 SeekOrigin 枚举的一个值表示 : SeekOrigin 有三个值:Begin  Current   End。

aFile.Seek(8,SeekOrigin.Begin)---------将文件的指针移动到第八个字节。起始位置就是文件的第一个字节。

aFile.Seek(-5,SeekOrigin.End); 从文件的末尾向前查找五个字节。。

aFile.Seek(2,SeekOrigin.Current);

FileStream.Seek 方法

将该流的当前位置设置为给定值。

命名空间:System.IO
程序集:mscorlib(在 mscorlib.dll 中)

语法

 
    
public override long Seek (
long offset,
SeekOrigin origin
)
范例:
using System;
using System.IO;

class FStream
{
static void Main()
{
const string fileName = " Test#@@#.dat " ;

// Create random data to write to the file.
byte [] dataArray = new byte [ 100000 ];
new Random().NextBytes(dataArray);

using (FileStream
fileStream
= new FileStream(fileName, FileMode.Create))
{
// Write the data to the file, byte by byte.
for ( int i = 0 ; i < dataArray.Length; i ++ )
{
fileStream.WriteByte(dataArray[i]);
}

// Set the stream position to the beginning of the file.
fileStream.Seek( 0 , SeekOrigin.Begin);

// Read and verify the data.
for ( int i = 0 ; i < fileStream.Length; i ++ )
{
if (dataArray[i] != fileStream.ReadByte())
{
Console.WriteLine(
" Error writing data. " );
return ;
}
}
Console.WriteLine(
" The data was written to {0} " +
" and verified. " , fileStream.Name);
}
}
}

转载于:https://www.cnblogs.com/gyweiUSTC/articles/2088673.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值