zoukankan      html  css  js  c++  java
  • C# 文件的一些基本操作(转)//用C#读写ini配置文件

    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: esta.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);
     }
    }
     
    -------------------------------------------------------
  • 相关阅读:
    手写Promise(转)
    阻止element组件中的<el-input/>的粘贴功能(转)
    js 对象深拷贝函数
    20182301 2019-2020-1《程序设计与数据结构》课程总结
    20182301 2019-2020-1 《数据结构与面向对象程序设计》实验9报告
    团队博客第二周——DIG
    20182301 2019-2020-1 《数据结构与面向对象程序设计》第十周学习总结
    《团队作业第一周》团队作业——DIG
    20182301 2019-2020-1 《数据结构与面向对象程序设计》哈夫曼实验报告
    20182301 2019-2020-1 《数据结构与面向对象程序设计》第9周学习总结
  • 原文地址:https://www.cnblogs.com/meimao5211/p/3333930.html
Copyright © 2011-2022 走看看