IO 使用File创建文本 streamwrite 写入字符,streamread输出字符
1.利用File.CreateText()来创建文本文件。
代码如下:
代码如下:
View Code
static void Main(string[] args)
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
try
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("this is my name");
sw.WriteLine("what about you");
sw.Write("?I fine");
}
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
try
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("this is my name");
sw.WriteLine("what about you");
sw.Write("?I fine");
}
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
使用streamRead来读取文件的内容
代码如下:
View Code
string path = @"c:\temp\MyTest.txt";
if (File.Exists(path))
{
File.Delete(path);
}
if (!File.Exists(path))
{
try
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("this is my name");
sw.WriteLine("what about you");
sw.Write("?I fine");
}
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s == "?I fine")
continue;
Console.WriteLine(s);
}
}
Console.ReadLine();
}
if (File.Exists(path))
{
File.Delete(path);
}
if (!File.Exists(path))
{
try
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("this is my name");
sw.WriteLine("what about you");
sw.Write("?I fine");
}
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s == "?I fine")
continue;
Console.WriteLine(s);
}
}
Console.ReadLine();
}