1.利用File.CreateText()来创建文本文件。
代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8d7ccecf228dc26a5694d4a02490ce86.png)
代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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来读取文件的内容
![](https://i-blog.csdnimg.cn/blog_migrate/c2f2c23b23b98c960a37ef008787e759.png)
代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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();
}