1:BinaryReader:读取二进制文件
Stream 就像是一个通道,在.net运行时和文件之间建立一个桥梁, 然后通过StreamReader读取数据。
BaseStream就是操作streamreader的,返回的结果就是streamreader
StreamReader是以一种特定的编码输入字符带缓冲的流字符读取器,而基础流就是它读取的未指定编码的无缓冲的字节流...
因此StreamReader可能缓冲输入使基础流的位置与StreamReader的位置不匹配,字符流的长度和基础流的字节长度也不见得相同...
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
br.BaseStream.Seek(0, SeekOrigin.Begin);
1、新建一个文件流。
2、转换为二进制流。
3、设置当前流的位置,即开始位置。像是一个标识一样,即指向开始读取的位置。
PS:Seek(0, SeekOrigin.Begin)的意思是在流的开始位置(SeekOrigin.Begin)偏移零位。如果为Seek(6, SeekOrigin.Begin)即为在流的开始位置(SeekOrigin.Begin)偏移6位
当要写入的文件名的路径没有给时,只给出了文件名,默认写入到文件的bin\debug中,学习了FileStream的使用,BinaryReader,BaseStream的使用。
class Program
{
static void Main(string[] args)
{
string filePath = @"D:\vivien.tang\桌面\614问题总结.docx";
string save = "save.txt";//这里的文件路径没有给出,只给出了文件名,在程序的debug中创建了文件名
FileStream fileReader = new FileStream(filePath,FileMode.Open,FileAccess.Read);
using(FileStream fileSave=new FileStream(save,FileMode.Create,FileAccess.Write,FileShare.ReadWrite))
{
BinaryReader binReader = new BinaryReader(fileReader,Encoding.Default);
BinaryWriter binWrite = new BinaryWriter(fileSave,Encoding.Default);
binReader.BaseStream.Position = 0;
while(binReader.BaseStream.Position<binReader.BaseStream.Length)
{
byte[] byBuffer = binReader.ReadBytes(1);
binWrite.Write((byte)byBuffer[0]);
}
binWrite.Flush();
}
string str = "TryToSave.txt";
using(FileStream file=new FileStream(str,FileMode.Create,FileAccess.Write))
{
file.Write(Encoding.Default.GetBytes("123"), 0, "123".Length);
}
fileReader.Close();
fileReader.Dispose();
Console.ReadKey();
}
readBytes(int length):从当前流中读取指定的字节数以写入字节数组中,并将当前位置前移相应的字节数.
FileStream fs =new FileStream(file_path,FileMode.Open,FileAccess.Read);//创建一个文件流
BinaryReader reader = new BinaryReader(fs);//以二进制的形式读取文件,转换为二进制流
BinaryWriter bw_ble_header = new BinaryWriter(writefs_ble_header, Encoding.Default);
reader.Close();
fs.Close();
fs.Dispose();
int32.Parse() :表示将数字的字符串转换为32位的有符号的整数;
用法:public static int Parse(string )
若string 为空,出现异常:ArgumentNullException
若string格式不正确,出现异常:FormatException
若string的值小于MinValue或者大于MaxValue,出现异常:OverflowException
(int)234.3;是一种强制类型转换
Convert.ToInt32() 则可以将多种类型(包括 object 引用类型)的值转换为 int 类型,因为它有许多重载版本:
public static int ToInt32(object);
public static int ToInt32(bool);
public static int ToInt32(byte);
public static int ToInt32(char);
public static int ToInt32(decimal);
public static int ToInt32(double);
public static int ToInt32(short);
public static int ToInt32(long);
public static int ToInt32(sbyte);
public static int ToInt32(string);