在操作文本文档时,发现改变文档的后缀名,只要相应的代码与该后缀名一致,仍然可以读写,以下依据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"而不会影响系统运行;