C# 文件的一些基本操作

2009-07-19  来自:博客园  字体大小:【  
  • 摘要:介绍C#对文件的一些基本操作,读写等。

using System;
using System.IO;
using System.Text;

namespace Document.Bll
{
    /**//// <summary>
    /// Summary description for fileinfo.
    /// </summary>
    public class fileinfo
    {
        public fileinfo()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        
        
        获取某目录下的所有文件(包括子目录下文件)的数量#region 获取某目录下的所有文件(包括子目录下文件)的数量        
        public int GetFileNum(string Path)
        {
            int fileNum = 0;
            string[] fileList = System.IO.Directory.GetFileSystemEntries(Path);
            // 遍历所有的文件和目录
            foreach(string file in fileList)
            {
                if(System.IO.Directory.Exists(file))
                    GetFileNum(file);
                else
                    fileNum++;
            }            
            return fileNum;
        }
        #endregion

获取某目录下的所有文件(包括子目录下文件)的大小#region 获取某目录下的所有文件(包括子目录下文件)的大小
        public long GetDirectoryLength(string dirPath)
        {
            if(!Directory.Exists(dirPath))
                return 0;
            long len=0;
            DirectoryInfo di=new DirectoryInfo(dirPath);
            foreach(FileInfo fi in di.GetFiles())
            {
                len+=fi.Length;
            }
            DirectoryInfo[] dis=di.GetDirectories();
            if(dis.Length>0)
            {
                for(int i=0;i<dis.Length;i++)
                {
                    len+=GetDirectoryLength(dis[i].FullName);
                }
            }
            return len;
        }
        #endregion

读取文件#region 读取文件
        private string file_get_contents(string path)
        {
            StringBuilder s=new StringBuilder();
            using (StreamReader sr = new StreamReader(path,System.Text.Encoding.GetEncoding ("GB2312"))) 
            {
                        string line;
                            while ((line = sr.ReadLine()) != null)
                {
                    s.Append(line);
                }
            }            
            return s.ToString();
        }
        #endregion

写文件#region 写文件
        public static void writefile() 
        {
            StreamWriter sw = new StreamWriter("TestFile.txt",true,System.Text.Encoding.GetEncoding("GB2312")) ;
            // Add some text to the file.
            sw.Write("This is the ");
            sw.WriteLine("header for the file.");
            sw.WriteLine("-------------------");
            // Arbitrary objects can also be written to the file.
            sw.Write("The date is: ");
            sw.WriteLine(DateTime.Now);
        }
        #endregion

System.IO.Path#region System.IO.Path
        private void System_IO_Path()
        {
            string path=@"c:\test\a.txt";

string ChangeExtension=System.IO.Path.ChangeExtension(path,".old");//更改路径字符串的扩展名。 
            string CombinePath=System.IO.Path.Combine(@"c:\","b.txt");//合并两个路径字符串。 
            string DirectoryName=System.IO.Path.GetDirectoryName(path);//返回指定路径字符串的目录信息。 
            string Extension=System.IO.Path.GetExtension(path);//返回指定的路径字符串的扩展名。 
            string FileName=System.IO.Path.GetFileName(path);//返回指定路径字符串的文件名和扩展名。
            string FileNameWithoutExtension=System.IO.Path.GetFileNameWithoutExtension(path); //返回不具有扩展名的指定路径字符串的文件名。 
            string FullPath=System.IO.Path.GetFullPath(path);//返回指定路径字符串的绝对路径。 
            string PathRoot=System.IO.Path.GetPathRoot(path);//获取指定路径的根目录信息。 
            string TempFileName=System.IO.Path.GetTempFileName();//返回唯一临时文件名并在磁盘上通过该名称创建零字节文件。 
            string TempPath=System.IO.Path.GetTempPath();//返回当前系统的临时文件夹的路径。 
            string HasExtension=System.IO.Path.HasExtension(path).ToString();//确定路径是否包括文件扩展名。 
            string IsPathRooted=System.IO.Path.IsPathRooted(path).ToString();//获取一个值,该值指示指定的路径字符串是包含绝对路径信息还是包含相对路径信息。
        }

#endregion
    }
}

出处:http://blog.csdn.net/whfyc/archive/2006/12/19/1449237.aspx

----------------------------------------------------------------------------------------------------------

用C#读写ini配置文件

INI就是扩展名为"INI"的文件,其实他本身是个文本文件,可以用记事本打工,主要存放的是用户所做的选择或系统的各种参数.
INI文件其实并不是普通的文本文件.它有自己的结构.由若干段落(SECTION)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键字(KEYWORD)和一个等号,等号右边就是关键字的值(VALUE).例如:
[Section1]
    KeyWord1 = Value1
    KeyWord2 = Value2
    ...
[Section2]
    KeyWord3 = Value3
    KeyWord4 = Value4

C#命名空间中没有直接读写INI的类,当然如果你把INT当成文本文件用System.IO类来读写算我没说.
我现在介绍的是系统处理INI的方法.
虽然C#中没有,但是在"kernel32.dll"这个文件中有Win32的API函数--WritePrivateProfileString()和GetPrivateProfileString()
C#声明INI文件的写操作函数WritePrivateProfileString():

[DllImport( "kernel32" )]
  private static extern long WritePrivateProfileString ( string section ,string key , string val 
, string filePath ) ;

参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。
C#申明INI文件的读操作函数GetPrivateProfileString():

[DllImport("kernel32")]
 private static extern int GetPrivateProfileString ( string section ,
  string key , string def , StringBuilder retVal ,
  int size , string filePath ) ;

参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称。

下面是一个读写INI文件的类:

public class INIClass
{
 public string inipath;
 [DllImport("kernel32")]
 private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
 [DllImport("kernel32")]
 private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
 /// <summary>
 /// 构造方法
 /// </summary>
 /// <param name="INIPath">文件路径</param>
 public INIClass(string INIPath)
 {
  inipath = INIPath;
 }
 /// <summary>
 /// 写入INI文件
 /// </summary>
 /// <param name="Section">项目名称(如 [TypeName] )</param>
 /// <param name="Key">键</param>
 /// <param name="Value">值</param>
 public void IniWriteValue(string Section,string Key,string Value)
 {
  WritePrivateProfileString(Section,Key,Value,this.inipath);
 }
 /// <summary>
 /// 读出INI文件
 /// </summary>
 /// <param name="Section">项目名称(如 [TypeName] )</param>
 /// <param name="Key">键</param>
 public string IniReadValue(string Section,string Key)
 {
  StringBuilder temp = new StringBuilder(500);
  int i = GetPrivateProfileString(Section,Key,"",temp,500,this.inipath);
  return temp.ToString();
 }
 /// <summary>
 /// 验证文件是否存在
 /// </summary>
 /// <returns>布尔值</returns>
 public bool ExistINIFile()
 {
  return File.Exists(inipath);
 }
}
 
-------------------------------------------------------

C# 文件的一些基本操作(转)//用C#读写ini配置文件的更多相关文章

  1. 谁能在同一文件序列化多个对象并随机读写(反序列化)?BinaryFormatter、SoapFormatter、XmlSerializer还是BinaryReader

    谁能在同一文件序列化多个对象并随机读写(反序列化)?BinaryFormatter.SoapFormatter.XmlSerializer还是BinaryReader 随机反序列化器 +BIT祝威+悄 ...

  2. c# 利用动态库DllImport("kernel32")读写ini文件(提供Dmo下载)

    c# 利用动态库DllImport("kernel32")读写ini文件 自从读了设计模式,真的会改变一个程序员的习惯.我觉得嘛,经验也可以从一个人的习惯看得出来,看他的代码编写习 ...

  3. 「C语言」文件的概念与简单数据流的读写函数

    写完「C语言」单链表/双向链表的建立/遍历/插入/删除 后,如何将内存中的链表信息及时的保存到文件中,又能够及时的从文件中读取出来进行处理,便需要用到”文件“的相关知识点进行文件的输入.输出. 其实, ...

  4. VB读写INI文件的四个函数以及相关API详细说明

    WritePrivateProfileString函数说明  来源:http://blog.csdn.net/wjb9921/article/details/2005000 在我们写的程序当中,总有一 ...

  5. C# 读写INI 文件

    INI 格式: [Section1] KeyWord1 = Value1 KeyWord2 = Value2 ... [Section2] KeyWord3 = Value3 KeyWord4 = V ...

  6. WIN32读写INI文件方法

      在程序中经常要用到设置或者其他少量数据的存盘,以便程序在下一次执行的时候可以使用,比如说保存本次程序执行时窗口的位置.大小.一些用户设置的 数据等等,在 Dos 下编程的时候,我们一般自己产生一个 ...

  7. oracle读写文件--利用utl_file包对磁盘文件的读写操作

    oracle读写文件--利用utl_file包对磁盘文件的读写操作 摘要: 用户提出一个需求,即ORACLE中的一个表存储了照片信息,字段类型为BLOB,要求能导出成文件形式. 本想写个C#程序来做, ...

  8. 读写ini文件

    C# 使用文件流来读写ini文件 背景 之前采用ini文件作为程序的配置文件,觉得这种结构简单明了,配置起来也挺方便.然后操作方式是通过WindowsAPI,然后再网上找到一个基于WindowsAPI ...

  9. 在 WinCe 平台读写 ini 文件

    在上篇文章开发 windows mobile 上的今日插件时,我发现 wince 平台上不支持例如 GetPrivateProfileString 等相关 API 函数.在网络上我并没有找到令我满意的 ...

随机推荐

  1. 【PostgreSQL-9.6.3】分区表

    PostgreSQL中的分区表是通过表继承来实现的(表继承博客http://www.cnblogs.com/NextAction/p/7366607.html).创建分区表的步骤如下: (1)创建“父 ...

  2. Resetting the SMC & PRAM

    Resetting the SMC & PRAM on portables with a battery you should not remove on your own 1. Shut d ...

  3. SpringMVC参数绑定、Post乱码解决方法

    从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上. springmvc中,接收页面提交的数据是通过方法形参来接收.而不是在control ...

  4. 浅谈animation里的forwards

    forwards可译为向前走, animation-fill-mode(动画填充模式),定义动画播放时间之外的状态 顾名思义,就是在动画播放完了之后给它一个状态 animation-fill-mode ...

  5. select 多选 和单选,分组

    <select name="group"> <option value="1">北京</option> <option ...

  6. 六、Scrapy中Download Middleware的用法

    本文转载自: https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/downloader-middleware.html https://doc. ...

  7. MySQL之中文乱码问题

    创建 my.ini 文件,在该文件中添加以下内容,放在安装好的mysql根路径下: [client] default-character-set=utf8 [mysql] # 设置mysql客户端默认 ...

  8. centos 7中 yum安装jdk

    yum安装jdk的好处就是不需要手动再配置环境变量,所有的变量都是自动生成 1.检查系统是否存在jdk,存在删除原版jdk 如果没有信息输出,则表示没有安装jdk rpm -qa |grep java ...

  9. 00.continue break return的使用场景

    continue continue 语句跳出本次循环,而break跳出整个循环. continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环. continue语句用在w ...

  10. Flask - 请求处理流程和上下文源码分析

    目录 Flask - 请求处理流程和上下文 WSGI Flask的上下文对象及源码解析 0. 请求入口 1.请求上下文对象的创建 2. 将请求上下文和应用上下文入栈 3.根据请求的URl执行响应的视图 ...