c# 读写文本文件,二进制文件

/// <summary>

/// 读取二进制文件

/// </summary>

/// <param name="filename"></param>

private void ReadBinaryFiles(string filename)

{

FileStream filesstream = new FileStream(filename, FileMode.Create);

BinaryWriter objBinaryWriter = new BinaryWriter(filesstream);

for (int index = 0; index < 20; index++)

{

objBinaryWriter.Write((int)index);

}

objBinaryWriter.Close();

filesstream.Close();

}

/// <summary>

/// 写入二进制文件

/// </summary>

/// <param name="filepath"></param>

private void WriteBinaryFiles(string filepath)

{

if (!File.Exists(filepath))

{

//文件不存在

}

else

{

FileStream filestream = new FileStream(filepath, FileMode.Open, FileAccess.Read);

BinaryReader objBinaryReader = new BinaryReader(filestream);

try

{

while (true)

{

//objBinaryReader.ReadInt32();

}

}

catch (Exception ex)

{

//已到文件结尾

}

}

}

File 类:

Create(string FilePath)

在指定路径下创建具有指定名称的文件。此方法返回一个FileStream 对象

OpenRead(string FilePath)

打开一个现有文件来读取数据

AppendText(string FilePah)

允许向文本添加文本

Copy(string SourceFilePath,string DestinationPath)

按指定的路径将源文件的内容复制到目标文件中。如果目标不存在,则在指定的路径中以指定的名称新建一个文件

Delete(string filePath)

删除指定路径的文件

Exists(string filePath)

验证指定路径是否存在具有指定名称的文件。该方法返回一个布尔值

/// <summary>

/// 写入文件

/// </summary>

/// <param name="filename"></param>

/// <param name="filecontent"></param>

private void SaveFiles(string filename,string filecontent)

{

FileStream fs;

try

{

fs = File.Create(filename);

}

catch (Exception ex)

{

throw ex;

}

byte[] content = new UTF8Encoding(true).GetBytes(filecontent);

try

{

fs.Write(content, 0, content.Length);

fs.Flush();

}

catch (Exception ex)

{

throw ex;

}

finally

{

fs.Close();

}

}

/// <summary>

/// 保存文件

/// </summary>

/// <param name="path"></param>

private void ReadFiles(string path)

{

try

{

if (!File.Exists(path))

{

//文件不存在

}

else

{

//打开流读取

FileStream fs = File.OpenRead(path);

//创建一个byte 数组以读取数据

byte[] arr = new byte[100];

UTF8Encoding data = new UTF8Encoding(true);

//继续读完文件的所有数据

while (fs.Read(arr, 0, arr.Length) > 0)

{

//data.GetString(arr);

}

}

}

catch (Exception ex)

{

throw ex;

}