1. txt文件

  1. /// <summary>
  2. /// 读文本文件信息
  3. /// </summary>
  4. /// <param name="FilePath"></param>
  5. /// <returns></returns>
  6. public static List<string> ReadTxtFile(string FilePath)
  7. {
  8. List<string> strList = new List<string>();
  9.  
  10. System.IO.FileStream FS = null;
  11. System.IO.StreamReader SR = null;
  12. if (System.IO.File.Exists(FilePath) )
  13. {
  14. try
  15. {
  16. if (strList == null)
  17. strList = new List<string>();
  18.  
  19. //using自动释放资源
  20. using (FS = new System.IO.FileStream(FilePath, System.IO.FileMode.Open))
  21. {
  22. SR = new System.IO.StreamReader(FS, System.Text.Encoding.Default);
  23. string Line = null;
  24. System.Drawing.Color color = new System.Drawing.Color();
  25. string[] rgb = new string[];
  26.  
  27. for (Line = SR.ReadLine(); Line != null; Line = SR.ReadLine())
  28. {
  29. if (!(Line.Trim() == ""))
  30. {
  31. strList.Add(Line);
  32. }
  33. }
  34.  
  35. }
  36. }
  37. catch (Exception ex)
  38. {
  39. throw (ex);
  40. }
  41. finally
  42. {
  43. if (SR != null)
  44. {
  45. SR.Dispose();
  46. SR.Close();
  47. }
  48. if (FS != null)
  49. {
  50. FS.Dispose();
  51. FS.Close();
  52. }
  53. }
  54. }
  55. else
  56. {
  57. strList = null;
  58. }
  59. return strList;
  60. }

读txt文件操作

  1. /// <summary>
  2. /// 保存文本文件信息
  3. /// </summary>
  4. /// <param name="psList">要写入文件的信息</param>
  5. /// <param name="filepath">存放文件的绝对路径</param>
  6. /// <returns></returns>
  7. public static bool SaveToTxtFile(List<string> psList,string filepath)
  8. {
  9. bool bResult = false;
  10. System.IO.FileStream FS = null;
  11. System.IO.StreamWriter SW = null;
  12. try
  13. {
  14. //新建文件流
  15. FS = new System.IO.FileStream(filepath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
  16. //建立文件对应的输入流
  17. SW = new System.IO.StreamWriter(FS);
  18.  
  19. foreach (string ps in psList)
  20. {
  21. SW.Write(ps+"\r\n");
  22. }
  23. bResult = true;
  24. }
  25. catch
  26. {
  27. bResult = false;
  28. }
  29. finally
  30. {
  31. if (SW != null)
  32. {
  33. SW.Close();
  34. }
  35. if (FS != null)
  36. {
  37. FS.Close();
  38. }
  39. }
  40. return bResult;
  41. }

写txt文件操作

2. xml文件

  1. XmlDocument xmldoc = new XmlDocument();//声明一个xml文档操作类的新实例
  2. string path = System.Windows.Forms.Application.StartupPath + @"../../../";
  3. Directory.SetCurrentDirectory(path);
  4. string portpath = Directory.GetCurrentDirectory() + @"\Program\FeedBackSetting.xml";//存放xml文件的绝对路径
  5. xmldoc.Load(portpath);
  6. XmlNode node = xmldoc.SelectSingleNode("FeedBack");//找到xml中的一个节点
  7.  
  8. node.SelectSingleNode("ThreShold").InnerText = txtThreshold.Text;
  9. node.SelectSingleNode("Sensitivity").InnerText = txtSensitivity.Text;
  10. node.SelectSingleNode("Speed").InnerText = txtSpeed.Text;
  11. xmldoc.Save(portpath);

XML文件读、修改操作

c#代码创建xml文件在看下??

3. ini文件

INI文件就是扩展名为“ini”的文件。在Windows系统中,INI文件是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。该文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件,来改变应用程序和系统的很多配置。但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。但在某些场合,INI文件还拥有其不可替代的地位。

INI文件的结构
INI文件是一种按照特点方式排列的文本文件。每一个INI文件构成都非常类似,由若干段落(section)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键词(keyword)和一个等号,等号右边的就是关键字对应的值(value)。其一般形式如下:
[Section1]
  KeyWord1 = Valuel
  KeyWord2 = Value2
   ……
[Section2]
  KeyWord3 = Value3
  KeyWord4 = Value4

注意:ini文件的第一行需要空出,不保留任何信息。(因项目中经常出现因为ini文件的数据顶格而产生的各种问题)

C#和Win32 API函数

C#并不像C++,拥有属于自己的类库。C#使用的类库是.Net框架为所有.Net程序开发提供的一个共有的类库——.Net FrameWork SDK。虽然.Net FrameWork SDK内容十分庞大,功能也非常强大,但还不能面面俱到,至少它并没有提供直接操作INI文件所需要的相关的类。在本文中,C#操作INI文件使用的是Windows系统自带Win32的API函数——WritePrivateProfileString()和GetPrivateProfileString()函数。这二个函数都位于“kernel32.dll”文件中。

我们知道在C#中使用的类库都是托管代码(Managed Code)文件,而Win32的API函数所处的文件,都是非托管代码(Unmanaged Code)文件。这就导致了在C#中不可能直接使用这些非托管代码文件中的函数。好在.Net框架为了保持对下的兼容,也为了充分利用以前的资源,提出了互操作,通过互操作可以实现对Win32的API函数的调用。互操作不仅适用于Win32的API函数,还可以用来访问托管的COM对象。C#中对Win32的API函数的互操作是通过命名空间“System.Runtime.InteropServices”中的“DllImport”特征类来实现的。它的主要作用是指示此属性化方法是作为非托管DLL的输出实现的。下面代码就是在C#利用命名空间“System.Runtime.InteropServices”中的“DllImport”特征类申明上面二个Win32的API函数:

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文件的完整路径和名称。

  1. using System.Runtime.InteropServices;
  2.  
  3. #region ini文件读写
  4. /*写数据函数参数说明:
  5. * section:INI文件中的段落;
  6. * key:INI文件中的关键字;
  7. * val:INI文件中关键字的数值;
  8. * filePath:INI文件的完整的路径和名称。
  9. */
  10. [DllImport("kernel32")]
  11. public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
  12. /*读数据函数参数说明:
  13. section:INI文件中的段落名称;
  14. * key:INI文件中的关键字;
  15. * def:无法读取时候时候的缺省数值;
  16. * retVal:读取数值;
  17. * size:数值的大小;
  18. * filePath:INI文件的完整路径和名称。
  19. */
  20. [DllImport("kernel32")]
  21. public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
  22. #endregion
  23.  
  24. //获取ini文件
  25. private string GetPortName()
  26. {
  27. string port = "";
  28. string section = "COM";//INI文件中的段落名称
  29. string key = "PortName";
  30. StringBuilder temp = new StringBuilder();
  31. string filepath = Application.StartupPath + @"\Amp.ini";
  32. try
  33. {
  34. Common.GetPrivateProfileString(section, key, "没有找到配置数据!", temp, , filepath);
  35. port = temp.ToString();
  36. if (port == "没有找到配置数据!")
  37. {
  38. port = "";
  39. }
  40. }
  41. catch
  42. {
  43. port = "";
  44. }
  45. return port;
  46.  
  47. }
  48.  
  49. //保存ini文件
  50. private void SaveToAmpIni(string section, string key, string val)
  51. {
  52. string filename = Application.StartupPath + @"\Amp.ini";
  53. Common.WritePrivateProfileString(section, key, val, filename);
  54. }

ini文件读写示例

c# 文件操作 txt、xml、ini的更多相关文章

  1. python基础——15(加密、excel操作、ini文件操作、xml操作模块及数据格式分类)

    一.加密模块 1.有解密的加密方式(base64) #base64加密 import base64 str_encrypt = input("输入要加密的字符串:\n") base ...

  2. 27、shutil文件操作、xml、subprocess运行子程序模块(了解)

    一.shutil模块(了解):高级的文件.文件夹.压缩包处理模块. import shutil # shutil.copyfileobj(fsrc, fdst[, length]),将文件内容拷贝到另 ...

  3. Day05 (黑客成长日记) 文件操作系列

    文件操作: 1.以什么编码方式输出,就以什么编码方式打开 f = open('d:\文件操作.txt',mode='r',encoding='GB2312') G = f.read() print(G ...

  4. 我来讲讲在c#中怎么进行xml文件操作吧,主要是讲解增删改查!

    我把我写的四种方法代码贴上来吧,照着写没啥问题. 注: <bookstore> <book> <Id>1</Id> <tate>2010-1 ...

  5. C# - 操作大型XML文件

    对于小型XML文件,利用XDocument和XMLDocument可以很方便进行读写(推荐XDocument),但问题是XDocument和XMLDocument是In-Memory类型的,随着文件大 ...

  6. ini文件操作

    Config.ini 文件操作 [SYS] sysname=hy company=hyhy tel=2 using System; using System.Collections.Generic; ...

  7. matlab文件操作及读txt文件(fopen,fseek,fread,fclose)

    文件操作是一种重要的输入输出方式,即从数据文件读取数据或将结果写入数据文件.MATLAB提供了一系列低层输入输出函数,专门用于文件操作. 1.文件的打开与关闭 1)打开文件 在读写文件之前,必须先用f ...

  8. ini 文件操作记要(1): 使用 TIniFile

    ini 文件操作记要(1): 使用 TIniFile unit Unit1; interface uses   Windows, Messages, SysUtils, Variants, Class ...

  9. winform INI文件操作辅助类

    using System;using System.Runtime.InteropServices;using System.Text; namespace connectCMCC.Utils{ // ...

随机推荐

  1. GPU bubbles

    https://software.intel.com/en-us/articles/performance-analysis-and-optimization-for-pc-based-vr-appl ...

  2. Hadoop 添加删除Slave

    Hadoop 添加删除Slave @(Hadoop) 在hdfs-site.xml文件中添加如下配置: <property> <name>dfs.hosts</name& ...

  3. Spring框架学习(4)spring整合hibernate

    内容源自:spring整合hibernate    spring整合注解形式的hibernate 这里和上一部分学习一样用了模板模式, 将hibernate开发流程封装在ORM层提供的模板类Hiber ...

  4. 【转】Go maps in action

    原文: https://blog.golang.org/go-maps-in-action ------------------------------------------------------ ...

  5. 转:android studio 改编译区背景色

    http://blog.csdn.net/zhuhai__yizhi/article/details/44017609 最近开始学习使用android studio想设置背景颜色,不过上网找的全都是复 ...

  6. docker学习笔记二:常用命令

    docker学习笔记二:常用命令 查看docker常用命令 docker --help 返回结果如下: 其中常用的命令如下: 1.image相关操作 展示所有的image: 删除image: rmi ...

  7. 我如何向HRMM介绍MICROSERVICE

    一天我司招才猫姐(HR 大人)问我,你给我解释一下 Microservice 是什么吧.故成此文.一切都是从一个创业公司开始的. 第一章:从集中到分权 最近的创业潮非常火爆,我禁不住诱惑也掺和了进去, ...

  8. 手机端UC浏览器,在java开发的下载功能中存在的问题?

    在java web开发中,不同浏览器对下载文件的格式有不同的要求,有时会出现视频,音频等文件无法下载的问题.我在开发中,也遇到类似的问题,觉得很苦恼. 经过百度和请教学习,得到2个解决方案. 首先得到 ...

  9. iOS sort array 数组排序里面的对象

    一:如下代码 //对数据按次数排序 NSArray *sortArrays = [pinCiDataArray sortedArrayUsingComparator:^NSComparisonResu ...

  10. 用Markdown写博客快速入门

    Markdown,简单来说,就是一种可以方便转换为HTML的带标记符号纯文本. 它是对我等键盘党的福音:我不用再费劲挪动鼠标去按加粗.设置段落了,用键盘输入所有文本,一气呵成. 最重要的是,cnblo ...