对文件进行操作

读取全部文件:

 StreamReader f2 = new StreamReader(Path, Encoding.Default);
 string s = f2.ReadToEnd();

一行行读取文件:

 using (StreamReader sr = new StreamReader(fullPath, Encoding.Default))
{

       while (!sr.EndOfStream)
       {
          rowStr = sr.ReadLine()
    }
}

清空文件内容:

  FileStream stream = File.Open(TargetFile, FileMode.OpenOrCreate, FileAccess.Write);
  stream.Seek(0, SeekOrigin.Begin);
  stream.SetLength(0);
  stream.Close();

 获取当前目录下的子目录

        /// <summary>
        ///获取指定目录及子目录中所有子目录列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
        {
            try
            {
                if (isSearchChild)
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show("NG:文件路径错误" + ex.Message);
                throw new Exception(ex.Message);
            }
        }

获取目录中文件:

        /// <summary>
        /// 获取目录中指定文件
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] ContainFile(string directoryPath, string searchPattern, bool isSearchChild)
        {
            string[] fileNames;
            try
            {
                if (!Directory.Exists(directoryPath))   //检测指定目录是否存在
                {
                    throw new FileNotFoundException();
                }
                if (isSearchChild)       //获取指定目录及子目录中所有文件列表
                {
                   return fileNames = Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return fileNames = Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
              
            
            }
            catch (Exception ex)
            {
                MessageBox.Show("NG:获取txt文件错误"+ ex.Message);
                throw new Exception(ex.Message);
              
            }
        }

 

posted @ 2021-01-29 15:42  越吃越瘦  阅读(60)  评论(0编辑  收藏  举报