C#代码关于文件文件夹的读写

1、读文件夹中的每个文件


            string strSeaPath = @"C:\Users\Administrator\Desktop\国内浮标站数据\国内浮标站数据\海洋要素";
         
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strSeaPath);
            foreach (System.IO.DirectoryInfo dirData in dir.GetDirectories())
            {
                System.IO.FileInfo file = dirData.GetFiles();
            
                string strOneLine;
                System.IO.StreamReader sr = new System.IO.StreamReader(file.FullName);
                while (!sr.EndOfStream)
                {
                    if ((strOneLine = sr.ReadLine()) != null)
                    {
                        strOneLine = strOneLine.Trim();
                       
                        WriteToTxt(strOneLine);
                    }

                }
                sr.Close();
                sr.Dispose();
            }           
2、将一行中连续多个空格替换成一个

 //将一行中多个连续的空格变成一个空格
                        strOneLine = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(strOneLine, " ");

3、将内容写入TXT文件

        #region WriteTxt():写入数据到TXT
        private void WriteTxt(string strFilePath, string strText)
        {
            FileStream fs = new FileStream(strFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            sw.Write(strText);
            sw.Flush();
            sw.Close();
        }
        #endregion WriteTxt():写入数据到TXT
4、判断文件目录是否存在
               string filePath = System.Windows.Forms.Application.StartupPath + "\\image\\" + FormSSKX.ZTH;
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
           if (yearFile.Directory.Exists)//文件夹是否存在
           {
           }
5、判断文件是否存在

            if (File.Exists(strfilepath))
            {
                
            }
6、清空TXT文件内容

 #region 清空TXT文件内容
        private void ClearTxt(String txtPath)
        {
            FileStream stream = File.Open(txtPath, FileMode.Truncate, FileAccess.ReadWrite);
            stream.Seek(0, SeekOrigin.Begin);
            stream.SetLength(0);
            FileStream stream = new FileStream(txtPath, FileMode.Truncate, FileAccess.ReadWrite);
            stream.Close();
            stream.Dispose();
        }  
        #endregion 清空TXT文件内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值