【NET】File操作练习笔记

这2天练习了一下File的操作,这种网上很多资料,但自己还是敲一敲,熟悉一下,主要方法:

1.创建或覆盖文件;

2.读取文件内容;

3.删除文件;

4.是否存在文件;

5.遍历查找所有文件,包括根目录和子目录

1.创建主要用FileStream流和StreamWriter写入,指定为UTF8编码

public static bool AddFile(string path,string content)
{
    try
    {
        if (isExistFile(path))//是否存在
        {
            DeleteFile(path);
        }

        FileStream fsObj = new FileStream(path, FileMode.Create);//创建或覆盖
        Encoding encode = Encoding.UTF8;
        StreamWriter swObj = new StreamWriter(fsObj, encode);
        swObj.Write(content);
        swObj.Close();
        fsObj.Close();
        return true;
    }
    catch
    {
        return false;
    }
}

2.读取文件的内容,主要用StreamRead读取文件路径

public static string ReadFile(string path)
        {
            string content = "";
            if(isExistFile(path))
            {
                StreamReader readObj = new StreamReader(path);
                content = readObj.ReadToEnd();
                readObj.Close();
                readObj.Dispose();
            }
            return content;
        }

3.删除文件,用的是System.IO.File.Delete,静态方法所以不用new

public static bool DeleteFile(string path)
{
    try
    {
        if (isExistFile(path))
        {
            File.Delete(path);
        }
        return true;
    }
    catch
    {
        return false;
    }
}

4.是否存在文件,用的是System.IO.File.Exist(),静态方法

        public static bool isExistFile(string path)
        {
            if (File.Exists(path)) { return true; }
            return false;
        }

5.遍历查找文件,分成2个方法,一个是读取当前文件夹里的文件,一个是遍历下一层文件夹和调用第1个方法。主要用FileSystemInfo来装载文件信息,判断是文件夹还是文件。

        /// <summary>
        /// 遍历这个文件夹的(一层)
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>

        public static FileSystemInfo[] GetFileDirectory(string path)
        {
            DirectoryInfo theDirectory = new DirectoryInfo(path);
            FileSystemInfo[] infoArray = theDirectory.GetFileSystemInfos();
            return infoArray;
        }

        /// <summary>
        /// 遍历文件夹的文件的文件(所有下层)
        /// </summary>
        /// <param name="path">物理路径</param>
        /// <param name="filesysteminfo">下层的所有文件</param>
        public static void GetFileDirectory_All(string path, ref List<FileSystemInfo> filesysteminfo)
        {
            //递归
            FileSystemInfo[] fsArray = GetFileDirectory(path);
            foreach (FileSystemInfo fObj in fsArray)
            {
                if (fObj is FileInfo)
                {
                    filesysteminfo.Add(fObj);
                }

                if (fObj is DirectoryInfo)
                {
                    GetFileDirectory_All(fObj.FullName, ref filesysteminfo);
                }
            }
        }
原文地址:https://www.cnblogs.com/laokchen/p/12841491.html