写入Text
public static void WriteText(string path,string value)
{
System.IO.StreamWriter swobj = System.IO.File.AppendText(path);
swobj.Write(value);
swobj.Flush();
swobj.Close();
}
读取Text
如果读取出来的内容乱码了,就需要
System.IO.StreamReader sr = new System.IO.StreamReader(path) 改成
System.IO.StreamReader sr = new System.IO.StreamReader(path, System.Text.Encoding.Default)
这样改过之后,我发现确实没有乱码,但是读取出来的内容不全了。所以,看下面另外一种读取方式。
public static string ReadText(string path)
{
string strData = "";
try
{
string line;
// 创建一个 StreamReader 的实例来读取文件 ,using 语句也能关闭 StreamReader
using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
{
// 从文件读取并显示行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
strData = line;
}
}
}
catch (Exception e)
{
// 向用户显示出错消息
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
return strData;
}
这种读取txt的方法,测试过后,正常。
private static string ReadFile(string fileName)
{
System.Text.StringBuilder str = new System.Text.StringBuilder();
using (FileStream fs = File.OpenRead(fileName))
{
long left = fs.Length;
int maxLength = 100;//每次读取的最大长度
int start = 0;//起始位置
int num = 0;//已读取长度
while (left > 0)
{
byte[] buffer = new byte[maxLength];//缓存读取结果
char[] cbuffer = new char[maxLength];
fs.Position = start;//读取开始的位置
num = 0;
if (left < maxLength)
{
num = fs.Read(buffer, 0, Convert.ToInt32(left));
}
else
{
num = fs.Read(buffer, 0, maxLength);
}
if (num == 0)
{
break;
}
start += num;
left -= num;
str = str.Append(System.Text.Encoding.Default.GetString(buffer));
}
}
return str.ToString();
}
创建和写入XML
public static void WriteXML(string Values,string filePath)
{
XmlDocument xmlDoc = new XmlDocument(); //引入using System.Xml 命名空间
//创建类型声明
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8","");
xmlDoc.AppendChild(node);
//创建根节点
XmlNode root = xmlDoc.CreateElement("Root");
xmlDoc.AppendChild(root);
//创建子节点,写入值
node = xmlDoc.CreateNode(XmlNodeType.Element, "Name", null);
node.InnerText = Values;
root.AppendChild(node);
xmlDoc.Save(filePath);
}
读取XML
private static string ReadXML(string fllePath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fllePath); //从指定的URL加载XML文档
XmlNode Values = xmlDoc.SelectSingleNode("父节点").SelectSingleNode("子节点");
string str = Values.InnerText; //获取到存入的值为 string
return str;
}