新建一个Log.txt文件
引入System.IO名称空间,用文件流
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace StreamWrite
{
class Program
{
static void Main(string[] args)
{
try
{
FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
bool truth = true;
// Write data to file.
sw.WriteLine("Hello to you.");
sw.WriteLine("It is now {0} and things are looking good.",
DateTime.Now.ToLongDateString());
sw.Write("More than that,");
sw.Write(" it's {0} that C# is fun.", truth);
sw.Close();
}
catch (IOException ex)
{
Console.WriteLine("An IOException has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
}
}
}
读取文件,这里介绍StreamReader对象
static void Main(string[] args)
{
string strLine;
try
{
FileStream aFile = new FileStream("Log.txt",FileMode.Open);
StreamReader sr = new StreamReader(aFile);
strLine = sr.ReadLine();
//Read data in line by line 这个兄台看的懂吧~一行一行的读取
while(strLine != null)
{
Console.WriteLine(strLine);
Line = sr.ReadLine();
}
sr.Close();
}catch (IOException ex)
{
Console.WriteLine("An IOException has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
}
另外对于简单的文档可以直接sr.ReadToEnd()从头读到尾,还有sr.Read() 返回类型char。这些兄台可以自己看书去学
引入System.IO名称空间,用文件流
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace StreamWrite
{
class Program
{
static void Main(string[] args)
{
try
{
FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
bool truth = true;
// Write data to file.
sw.WriteLine("Hello to you.");
sw.WriteLine("It is now {0} and things are looking good.",
DateTime.Now.ToLongDateString());
sw.Write("More than that,");
sw.Write(" it's {0} that C# is fun.", truth);
sw.Close();
}
catch (IOException ex)
{
Console.WriteLine("An IOException has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
}
}
}
读取文件,这里介绍StreamReader对象
static void Main(string[] args)
{
string strLine;
try
{
FileStream aFile = new FileStream("Log.txt",FileMode.Open);
StreamReader sr = new StreamReader(aFile);
strLine = sr.ReadLine();
//Read data in line by line 这个兄台看的懂吧~一行一行的读取
while(strLine != null)
{
Console.WriteLine(strLine);
Line = sr.ReadLine();
}
sr.Close();
}catch (IOException ex)
{
Console.WriteLine("An IOException has been thrown!");
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
}
另外对于简单的文档可以直接sr.ReadToEnd()从头读到尾,还有sr.Read() 返回类型char。这些兄台可以自己看书去学