关于文件操作

在操作文本文档时,发现改变文档的后缀名,只要相应的代码与该后缀名一致,仍然可以读写,以下依据C# 语言,提供了两种读写文本文档的方式。


1)通过使用系统API 函数进行读写,但是此种方式的读写需要有特定的书写规则,否则会出错,命名空间需要包括

using System.Text;
using System.Runtime.InteropServices;
using System.IO;

 	 //声明读写INI文件的API函数 
        [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);
        //写INI文件  
        public static void IniWriteValue(string Section, string Key, string Value ,string path)
        {         
           WritePrivateProfileString(Section, Key, Value, path);
        }

        //读取INI文件指定 
        public  static string IniReadValue(string Section, string Key ,string path)
        {
            StringBuilder temp = new StringBuilder(100);
            int i;        
            i = GetPrivateProfileString(Section, Key, "", temp, 100, path);
            return temp.ToString();
        }

2)依据传统的文件流形式读写文档;

using System;

using System.IO;

        public static void WriteString(string path,string filename, string text)
        {
            if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path);
            FileInfo fi = new FileInfo(path + @"\" + filename);
            try
            {
                FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Write);
                using (fs)
                {
                    StreamWriter w = new StreamWriter(fs);
                    w.BaseStream.Seek(0, SeekOrigin.End);
                    w.Write(text);
                    w.Flush();
                    w.Close();
                    fs.Close();
                }
            }
            catch (SystemException ex)
            {
                throw ex;
            }
        }

        public static string ReadString(string path)
        {
            string strtxt = "";
            try
            {
                string pp = path;
                StreamReader sr = new StreamReader(pp, Encoding.Default);
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    strtxt += line.ToString();
                }
                sr.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return strtxt;
        }

注: 对于文件名 filename 一栏中,可以是“test.txt”,"test.key","text.xx"而不会影响系统运行;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值