C#向文件写、读数据

时间:2022-08-12 20:58:19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; namespace FileTest
{
class Program
{
static void Main(string[] args)
{
WriteFile();
ReadFile(); Console.ReadKey();
} /// <summary>
/// 写、读文件
/// </summary>
static void WriteFile()
{
string pathUrl = @"E:\我的任务\其他\MyCodes_VS2013\MyCodes\TestFolder\WriteAndReadFile.txt"; try
{
if (File.Exists(pathUrl))
{
#region 向文件写入数据 Console.WriteLine("");
//以WriteAllBytes方式向文件中写入数据,可以操作除文本文件外的文件类型,比如音频文件,视频文件等
Console.WriteLine("以WriteAllBytes方式向文件中写入数据");
byte[] contentInByte = Encoding.GetEncoding("gb2312").GetBytes("以WriteAllBytes方式向文件中写入数据。"); ;
File.WriteAllBytes(pathUrl, contentInByte); Console.WriteLine("");
//以WriteAllLines方式向文件中写入数据
Console.WriteLine("以WriteAllLine方式向文件中写入数据");
string[] contentInString = new string[] { "以WriteAllLine方式向文件中写入数据。" };
File.WriteAllLines(pathUrl, contentInString, Encoding.GetEncoding("gb2312")); Console.WriteLine("");
//以WriteAllText方式向文件中写入数据
Console.WriteLine("以WriteAllText方式向文件中写入数据");
File.WriteAllText(pathUrl, "以WriteAllText方式向文件中写入数据。", Encoding.GetEncoding("gb2312"));
#endregion
                    #region  以上三种方会将文件原有数据覆盖,若想不覆盖原有数据,可以用下面两种方法;实现在原有数据后追加数据
//AppendAllLines方式向文件写入数据
File.AppendAllLines(pathUrl, new string[] { "AppendAllLine方式向文件写入数据" }, Encoding.GetEncoding("gb2312"));
//AppendAllText方式向文件写入数据
File.AppendAllText(pathUrl, "AppendAllText方式向文件写入数据", Encoding.GetEncoding("gb2312"));
#endregion
}
else
{
File.Create(pathUrl);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
} } static void ReadFile()
{
string pathUrl = @"E:\我的任务\其他\MyCodes_VS2013\MyCodes\TestFolder\WriteAndReadFile.txt"; try
{
if (File.Exists(pathUrl))
{
Console.WriteLine("");
#region 读取文件数据 //以ReadAllBytes方式读取数据
Console.WriteLine("以ReadAllBytes方式读取文件数据:");
byte[] readContentInByte = File.ReadAllBytes(pathUrl);
Console.WriteLine(Encoding.GetEncoding("gb2312").GetString(readContentInByte)); Console.WriteLine("");
//以ReadAllLine方式读取数据
Console.WriteLine("以ReadAllLine方式读取文件数据:");
string[] readContentInString = File.ReadAllLines(pathUrl, Encoding.GetEncoding("gbk"));
Console.WriteLine(readContentInString.Aggregate(string.Empty, (result, current) => result += current)); Console.WriteLine("");
//以ReadAllText方式读取数据
Console.WriteLine("以ReadAllTex方式读取文件数据:");
Console.WriteLine(File.ReadAllText(pathUrl, Encoding.GetEncoding("GBK"))); #endregion
}
else
{
File.Create(pathUrl);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
} }
}
}