C# 文件操作

http://msdn.microsoft.com/zh-cn/library/System.IO.File_methods.aspx

http://www.cnblogs.com/qinfei/archive/2005/11/03/268229.html

 

 1 //文本文件操作:创建/读取/拷贝/删除
 2 using System;
 3 using System.IO;
 4 class Test 
 5  {
 6     string path = @"f:\t.txt";
 7     public static void Main() 
 8     {       
 9        //创建并写入(将覆盖已有文件)
10       if (!File.Exists(path))
11        {          
12           using (StreamWriter sw = File.CreateText(path))
13           {
14              sw.WriteLine("Hello");
15           } 
16        }
17        //读取文件
18       using (StreamReader sr = File.OpenText(path)) 
19        {
20          string s = "";
21          while ((s = sr.ReadLine()) != null) 
22          {
23             Console.WriteLine(s);
24          }
25       }
26       //删除/拷贝
27      try 
28       {
29          File.Delete(path);
30          File.Copy(path, @"f:\tt.txt");
31       } 
32       catch (Exception e) 
33       {
34          Console.WriteLine("The process failed: {0}", e.ToString());
35       }
36     }
37  }
38 
39 
40 //流文件操作
41 private const string name = "Test.data";
42  public static void Main(String[] args) 
43  {
44     //打开文件()  ,或通过File创建立如:fs = File.Create(path, 1024)
45     FileStream fs = new FileStream(name, FileMode.CreateNew);
46      //转换为字节 写入数据(可写入中文)
47     Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
48      //字节数组,字节偏移量,最多写入的字节数
49     fs.Write(info, 0, info.Length);
50      w.Close();
51      fs.Close();
52      //打开文件
53     fs = new FileStream(name, FileMode.Open, FileAccess.Read);
54      //读取
55     BinaryReader r = new BinaryReader(fs);
56      for (int i = 0; i < 11; i++) 
57      {
58          Console.WriteLine(r.ReadInt32());
59      }
60      w.Close();
61      fs.Close();
62  }

 

 

文件操作

若要执行此操作...请参阅本主题中的示例...
创建文本文件 向文件写入文本
写入文本文件 向文件写入文本
读取文本文件 从文件读取文本
向文件中追加文本 File.AppendText FileInfo.AppendText
重命名或移动文件 File.Move FileInfo.MoveTo
删除文件 File.Delete FileInfo.Delete
复制文件 File.Copy FileInfo.CopyTo
获取文件大小 FileInfo.Length
获取文件属性 File.GetAttributes
设置文件属性 File.SetAttributes
确定文件是否存在 File.Exists
读取二进制文件 对刚创建的数据文件进行读取和写入
写入二进制文件 对刚创建的数据文件进行读取和写入
检索文件扩展名 Path.GetExtension
检索文件的完全限定路径 Path.GetFullPath
检索路径中的文件名和扩展名 Path.GetFileName
更改文件扩展名

Path.ChangeExtension

posted @ 2013-08-27 12:06  vivianC  阅读(211)  评论(0编辑  收藏  举报