• C#__基本的读写文件方式


    // 代码+注释 

    1. class Program
    2. {
    3. ///
    4. /// Path类:
    5. /// 不能实例化;提供了一些静态方法,更容易对路径名执行操作;(有兴趣可以自行了解)
    6. ///
    7. /// 读写文件:File类
    8. ///
    9. ///
    10. static void Main(string[] args)
    11. {
    12. // ReadAllText(): 打开一个文本文件,读取文件的所有行,然后关闭该文件
    13. Console.WriteLine(File.ReadAllText(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt"));
    14. /*
    15. 这是一个文本文件
    16. 小米南瓜是一种美味的食品
    17. 欢迎大家前来品尝
    18. */
    19. // 打开一个文本文件,读取文件的所有行,然后关闭该文件
    20. string[] strArray = File.ReadAllLines(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt");
    21. foreach(string str in strArray)
    22. {
    23. Console.Write(str);
    24. }
    25. Console.WriteLine();
    26. // 这是一个文本文件小米南瓜是一种美味的食品欢迎大家前来品尝
    27. // 打开一个二进制文件(将文件转换为二进制文件),将文件的内容读入一个字节数组(0~255),然后关闭该文件
    28. Byte[] byteArray = File.ReadAllBytes(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt");
    29. int i = 0;
    30. while (i < byteArray.Length)
    31. {
    32. if (15 == i % 16)
    33. {
    34. Console.WriteLine(byteArray[i]);
    35. }
    36. else
    37. {
    38. Console.Write(byteArray[i] + " ");
    39. }
    40. i++;
    41. }
    42. /*
    43. 239 187 191 232 191 153 230 152 175 228 184 128 228 184 170 230
    44. 150 135 230 156 172 230 150 135 228 187 182 13 10 229 176 143
    45. 231 177 179 229 141 151 231 147 156 230 152 175 228 184 128 231
    46. 167 141 231 190 142 229 145 179 231 154 132 233 163 159 229 147
    47. 129 13 10 230 172 162 232 191 142 229 164 167 229 174 182 229
    48. 137 141 230 157 165 229 147 129 229 176 157
    49. */
    50. // 创建一个新文件,向其中写入指定的字符串,然后关闭文件。 如果目标文件已存在,则覆盖该文件。
    51. File.WriteAllText(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt","Hello World!");
    52. Console.WriteLine(File.ReadAllText(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt"));
    53. // Hello World!
    54. // 创建一个新文件,在其中写入指定的字节数组,然后关闭该文件(注意:每打印一行会换行,实际行数为输入的数组+1)
    55. File.WriteAllLines(@"D:\C#编程\文件操作之FileInfo和DirectoryInfo\TextFile1.txt", new string[]{ "1","2","3"});
    56. /*
    57. * 1
    58. * 2
    59. * 3
    60. */
    61. // Read:在内存中读文件,一般情况下不使用(不推荐)
    62. }
    63. }

  • 相关阅读:
    【七夕】是时候展现专属于程序员的“浪漫”了
    生产者与消费者模型:餐厅吃饭问题
    TypeScript基础
    WPF 深入理解四、样式
    2022.8.15-8.21 AI行业周刊(第111期):AI行业定位
    Linux驱动开发 --- 架构方面的一些感悟
    30出头成为复旦博导,陈思明:敲代码和写诗,我两样都要
    go访问私有变量
    数商云DMS渠道商城系统全渠道营销场景应用举例,赋能日化行业增强渠道掌控力
    正则表达式的应用(前端写法)
  • 原文地址:https://blog.csdn.net/qq_57233919/article/details/132775164