一般的文件读写正常使用StreamReader、StreamWriter,如果是二进制的文件使用BinaryReader、BinaryWriter:
//使用FileStream文件
/// <summary>
/// 引用StreamWriter它涉及到文本文件的读写。StreamReader 和 StreamWriter 类有助于完成文本文件的读写。
/// </summary>
/// <param name="Needwriter">需要添加的数据、文字等等</param>
static void FileWrite(string path ,string Needwriter) {//该方法的参数是需要写入数据的文件路径(path),以及需要写入的数据(Needwriter)
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter(fs);
writer.BaseStream.Seek(fs.Length,SeekOrigin.Begin);//此处输入的数据将会在最后另起一行导入数据
writer.WriteLine(string.Format("Service Start at {0}", DateTime.Now.ToString()));
writer.WriteLine(Needwriter);
writer.Flush();
writer.Close();
}
/// <summary>
/// 二进制文件的读写,它涉及到二进制文件的读写。BinaryReader 和 BinaryWriter 类有助于完成二进制文件的读写。
/// </summary>
/// <param name="Needwriter">需要添加的数据、文字等等</param>
static void filewrite1(string path ,string Needwriter) {//该方法的参数是需要写入数据的文件路径(path),以及需要写入的数据(Needwriter)
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);//针对于二进制文件的读写,正常的文件读写建议使用StreamWriter、StreamReader
fs.Seek(fs.Length,SeekOrigin.End);
bw.Write(string.Format("Service Start at {0}:", DateTime.Now.ToString()));
bw.Write(Needwriter);
bw.Flush();
bw.Close();
}
/// <summary>
///
/// </summary>
/// <param name="Needwriter">需要添加的数据、文字等等</param>
static void filewrite2(,string path,string Needwriter) {//该方法的参数是需要写入数据的文件路径(path),以及需要写入的数据(Needwriter)
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);//此处是在所选的字符流的结尾直接添加输入的数据
m_streamWriter.WriteLine(string.Format("Service Start at {0}:", DateTime.Now.ToString()));
m_streamWriter.WriteLine(Needwriter);
m_streamWriter.Flush();
m_streamWriter.Close();
}
方法二为二进制的写入,与正常的文本写入存在差异: