C# code oFileStream = new FileStream("文件路径", FileMode.Create, FileAccess.Write, FileShare.ReadWrite); StreamWriter oStreamWriter = new StreamWriter(oFileStream, Encoding.Default); oStreamWriter.Write("要写入内容"); oStreamWriter.WriteLine(); oStreamWriter.Close(); oFileStream.Close();
读取
C# code oFileStream = new FileStream("文件路径", FileMode.Create, FileAccess.Write, FileShare.ReadWrite); StreamReader oStreamReader = new StreamReader(oFileStream, Encoding.Default); string _Text = oStreamReader.ReadToEnd(); oStreamReader.Close(); oFileStream.Close();
// <summary>
/// 写数据到文件
/// </summary>
/// <param name="strDataList">行数据列表 </param>
/// <param name="filename">文件名 </param>
/// <returns>是否成功 </returns>
public static bool WriteToFile(List <string> strDataList,string filename)
{
try
{
//Pass the filepath and filename to the StreamWriter Constructor
// StreamWriter sw = new StreamWriter(filename);
StreamWriter sw = new StreamWriter(filename,false,Encoding.GetEncoding("gb2312"));
sw.Write("", false);
//Write a line of text
foreach (string item in strDataList)
{
sw.WriteLine(item, true);
}
//Close the file
sw.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
/// <summary>
/// 从文件获取数据
/// </summary>
/// <param name="fileName">文件名 </param>
/// <returns>行数据列表 </returns>
public static List <string> ReadFromFile(string fileName)
{
List <string> dataList = new List <string>();
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader(fileName, Encoding.GetEncoding("gb2312"));
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
dataList.Add(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
}
catch (Exception e)
{
dataList = null;
}
return dataList;
}
private void WriteFile(string filepath,string str )
{
FileStream fs = (!File.Exists(filepath)) ? new FileStream(filepath, FileMode.Create) : File.Open(filepath, FileMode.Append);
//获得字节数组
byte[] data = new UTF8Encoding().GetBytes(str+'\n');
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
//调用
WriteFile(@"c:\ss.txt","给我分啊")