赞
踩
File.WriteAllText()
方法,通常用于将一些文本写入文件,要清除文件的内容,您只需使用以下命令将空文本写入文件即可以项目文件中的一个记事本为例子,代码如下:- using System;
- using System.IO;
-
- public class Example
- {
- public static void Main()
- {
- string path = @"D:\Test\data.txt";
- File.WriteAllText(path, string.Empty);
- }
- }
FileStream.SetLength()
方法,创建一个新的文件流,使用FileStream.SetLength()
方法,最后冲洗流。-
- using System;
- using System.IO;
-
- public class Example
- {
- public static void Main()
- {
- string path = @"D:\Test\data.txt";
- using (FileStream fs = new FileStream(path, FileMode.Open))
- {
- fs.SetLength(0);
- }
- }
- }
FileMode.Truncate
模式,然后关闭它。这将清除文件的内容,甚至不必调用 FileStream.SetLength()
方法。- using System;
- using System.IO;
-
- public class Example
- {
- public static void Main()
- {
- string path = @"D:\Test\data.txt";
- using (FileStream fs = new FileStream(path, FileMode.Truncate)) {
-
- }
- }
File.Create()
方法File.Create()
方法,如果文件不存在,则在指定路径创建一个文件。如果该文件确实存在,并且不是只读的,则内容将被覆盖。- using System;
- using System.IO;
-
- public class Example
- {
- public static void Main()
- {
- string path = @"D:\Test\data.txt";
- File.Create(path).Close();
- }
- }
- //Read a Text File 读取一个文本文件
- using System;
- using System.IO;
- namespace readwriteapp
- {
- class Class1
- {
- [STAThread]
- static void Main(string[] args)
- {
- String line;
- try
- {
-
- //将文件路径和文件名传递给StreamReader构造函数
- StreamReader sr = new StreamReader(@"D:\Test\data.txt");
- //读取文本的第一行
- line = sr.ReadLine();
- //继续读取,直到到达文件末尾
- while (line != null)
- {
- //将行写入控制台窗口
- Console.WriteLine(line);
- //读取下一行
- line = sr.ReadLine();
- }
- //关闭文件:将已打开的文件关闭,以便释放系统资源或进行其他操作。
- sr.Close();
- Console.ReadLine();
- }
- catch(Exception e)
- {
- Console.WriteLine("Exception: " + e.Message);
- }
- finally
- {
- //执行最后一个块
- Console.WriteLine("Executing finally block.");
- }
- }
- }
- }

- //Write a text file Version1
- using System;
- using System.IO;
- namespace readwriteapp
- {
- class Class1
- {
- [STAThread]
- static void Main(string[] args)
- {
- try
- {
- //将文件路径和文件名传递给StreamWriter构造函数
- StreamWriter sw = new StreamWriter(@"D:\Test\data.txt");
- //写第一行文字
- sw.WriteLine("Hello World!!");
- //写第二行文字
- sw.WriteLine("From the StreamWriter class");
- //关闭文件
- sw.Close();
- }
- catch(Exception e)
- {
- Console.WriteLine("Exception: " + e.Message);
- }
- finally
- {
- Console.WriteLine("Executing finally block.");
- }
- }
- }
- }

- //Write a text file - Version2
- using System;
- using System.IO;
- using System.Text;
- namespace readwriteapp
- {
- class Class1
- {
- [STAThread]
- static void Main(string[] args)
- {
- Int64 x;
- try
- {
- //打开文件
- StreamWriter sw = new StreamWriter(@"D:\Test\data.txt",true,Encoding.ASCII);
-
- //把数字1到10写在同一行上。
- for(x=0; x < 10; x++)
- {
- sw.Write(x);
- }
- //关闭文件
- sw.Close();
- }
- catch(Exception e)
- {
- Console.WriteLine("Exception: " + e.Message);
- }
- finally
- {
- Console.WriteLine("Executing finally block.");
- }
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。