zoukankan      html  css  js  c++  java
  • C# 写入文件,读取文件

    主要使用IO流的:Directory、File、Stream类来实现

    一、写入文件

                    //1.创建目录(文件夹)
                    string directoryPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"log";//使用当前程序的根目录
                    //directoryPath = @"c:/log";//或者存储在指定目录
                    if (Directory.Exists(directoryPath) == false)//没有该目录,则创建
                        Directory.CreateDirectory(directoryPath);
    
                    //2.创建文件
                    string fileName = "文件名称.txt";
                    string newName = Path.Combine(directoryPath, fileName);
                    if (System.IO.File.Exists(newName) == false)
                    {
                        FileStream fs = System.IO.File.Create(newName);
                        fs.Close(); fs.Dispose();
                    }
    
                    //3.在文件中写入内容
                    using (StreamWriter sw = new StreamWriter(newName, true))
                    {
                        sw.Write("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
                    }

    二、读取文件

    //newName跟上面一样,是要读取文件的路径
    
    System.IO.File.ReadAllText(newName);//读取所有内容
    
    string[] strList = System.IO.File.ReadAllLines(newName);//读取所有内容存储到数组里,每行是一个数组元素
  • 相关阅读:
    班课2
    班课2
    班课1
    lecture 2
    lecture 1
    使用node的fs读取文件
    使用Node.js搭建一个本地服务器
    Node.js前言
    简述ES6其他的东西
    ES6异步操作Thunk、co和async
  • 原文地址:https://www.cnblogs.com/liuzheng0612/p/15589073.html
Copyright © 2011-2022 走看看