关于文件操作
来源:互联网 发布:公知精英是什么意思 编辑:程序博客网 时间:2024/06/16 15:27
在操作文本文档时,发现改变文档的后缀名,只要相应的代码与该后缀名一致,仍然可以读写,以下依据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
- 关于文件操作集锦
- 关于文件操作集锦
- 关于文件操作
- 关于文件的操作
- 关于文件操作
- ABAP--关于文件操作
- 关于python文件操作
- 关于python文件操作
- 关于python文件操作
- 关于python文件操作
- 关于python文件操作
- 关于python文件操作
- 关于python文件操作
- 关于python文件操作
- ABAP--关于文件操作
- 关于python文件操作
- 关于python文件操作
- 关于python文件操作
- 《2017Android常用框架收录——Butterknife》
- Spark 自定义排序
- Android常用开源项目(四十五)
- GIT学习之路第四天 远程仓库
- sftp
- 关于文件操作
- jquery:Failed to load resource: the server responded with a status of 404 (Not Found)
- 100个高质量Java开发者博客
- 新路程------rtl8188的配置
- ElasticSearch5.5.1插件分类
- 初学者如何学java编程?某作者的笔记实录
- 3.linux的守护进程
- Python 正确重载运算符
- 高德地图JS开发之入门