文件的读取和写入

与AppentAllText方法类似,WreiteAllText可以将指定的字符串直接写入文件,WriteAllText方法的声明如下

创建一个新文件在其中写入指定的字符串数组,然后,关闭该文件,如果目标存已存在,则改写文件

public static void WriteAllText(string path ,string contents)

创建一个新文件在其中写入指定编码的字符串数组,然后,关闭该文件,如果目标存已存在,则改写文件

public static void WriteAllText(string path ,string contents, Encoding encoding )

下面使用WrtiiteAlltext 方法添加指定字符串数组到文本

 const string path = @"C:\oscar.txt";
            File.WriteAllText(path, "这是使用WriteAlltext方法添加的字符串!" + Environment.NewLine);
            File.WriteAllText(path, "这是用File类中的AppendAllText方法添加到文本的字符串,并且指定编码的格式为UTF-8", Encoding.UTF8);
            string str = File.ReadAllText(path);
            Console.WriteLine(str);
            /*
             * WriteAllText与AppendAlltext之间的区别是:WriteAllText会清楚现在文件中已经存有的文本,。写入新的文本而AppendAllText则是在文件的尾部添加文本
            从上面可以看出我添加了两次而结果只显示出来一次。
             */

与WriteAlltext类似的还有WriteAllLines和WriteAllBytes方法 ,

在指定文件中写如指定的字符数组,如果文件不存在,则创建文件,否则改写文件,

public static void WriteAllLines (sting path ,string []  countenes);

在指定文件中写如指定的字符数组,并且指定编码的形式 ,如果文件不存在,则创建文件,否则改写文件,

public static void WriteallLines(string path ,string [] contenes , Encoding encoding )

在指定文件中写如指定的字符数组,如果文件不存在,则创建文件,否则改写文件,

Public static void WriteAllBytes(string path ,Bytes[] bytes)

下面用这三种方法演示:

   const string path = @"C:\ oscar.txt ";
            string [] str = {"这是","使用","WriteLines","方法","添加","字符串"};
            File.WriteAllLines(path, str);
            string[] str1 = File.ReadAllLines(path);
            string bytestr = "这是使用WriteBytes方法添加字节数组";
            Byte[] bytes = Encoding.UTF8.GetBytes(bytestr.ToCharArray());
            File.WriteAllBytes(path, bytes);

            string str11 = File.ReadAllText(path);
            Console.WriteLine(str11);

原文地址:https://www.cnblogs.com/lichen396116416/p/1922485.html