C# 70-536 – Chapter 2 Input/Output (I/O)

  • 5936
  • 0
  • C#
  • 2011-05-11

C# 70-536 – Chapter 2

這章的重點在討論I/O,除了檔案系統以外還有一大堆Stream的用法。

相關類別:

FileSystem

最常用到的大概就是改檔案屬性,尤其是唯讀檔的操作:

 

string path = @"D:\controller.txt";

//利用File Utility判斷檔案是否唯讀
if ((File.GetAttributes(path) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
	File.SetAttributes(path, FileAttributes.Normal);
}

// set (add) hidden attribute (hide a file)
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
// delete/clear hidden attribute
File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.Hidden);

//利用FileInfo判斷檔案是否唯讀
FileInfo fInfo = new FileInfo(path);
if (fInfo.IsReadOnly == true)
{
	fInfo.IsReadOnly = false;
}

 

檔案讀取及寫入:(之前最常用來判斷是否讀到檔案結尾的大概是Peek,不過2.0以上有新屬性EndOfStream)

string path = @"D:\controller.txt";

//使用File.ReadAllText
string text = File.ReadAllText(path, Encoding.Default);
Console.WriteLine(text);

//使用StreamReader
using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
	text = sr.ReadToEnd();
	sr.Close();
	Console.WriteLine(text);
}

using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
	while (sr.Peek() >= 0) //回傳下一字元但不移動指標Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
	{
		Console.WriteLine(sr.ReadLine());
	}
	sr.Close();
}
using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
	while (!sr.EndOfStream) //判斷是否位於資料流末端Supported in: 3.5, 3.0, 2.0
	{
		Console.WriteLine(sr.ReadLine());
	}
	sr.Close();
}


//覆寫
File.WriteAllText(path, "File.WriteAllText\r\n");

//附加
byte[] b = Encoding.Default.GetBytes("FileStream.Write\r\n");
if (File.Exists(path))
{
	//使用FileStream
	//FileStream fs = File.OpenWrite(path);
	//FileStream fs = File.Open(path, FileMode.Append, FileAccess.Write);
	using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
	{
		fs.Write(b, 0, b.Length);
		fs.Close();
	}

	//使用StreamWriter
	using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
	{
		sw.WriteLine("StreamWriter.WriteLine");
		sw.Close();
	}
}

//使用BufferedStream,先將資料寫到緩衝區
using (FileStream newFile = File.Create(@"D:\newfile.txt"))
{
	BufferedStream buffered = new BufferedStream(newFile);
	StreamWriter sw = new StreamWriter(buffered);
	sw.WriteLine("Data...");
	sw.Close();
}

壓縮資料:GzipStream & DeflateStream (二個類別操作方式一模一樣)

/// <summary>
/// 壓縮資料
/// </summary>
/// <param name="inFilename"></param>
/// <param name="outFilename"></param>
static void CompressFile(string inFilename, string outFilename)
{
	if (File.Exists(inFilename))
	{
		FileStream inFS = File.OpenRead(inFilename);
		FileStream outFS = File.Create(outFilename);
		using (GZipStream gzStream = new GZipStream(outFS, CompressionMode.Compress))
		{
			int data;
			while ((data = inFS.ReadByte()) != -1)
			{
				gzStream.WriteByte((byte)data);
			}
			gzStream.Close();
		}
		outFS.Close();
		inFS.Close();
	}
}

使用隔離儲存區(isolated storage):

蹂躪大剛好有整理一篇比較詳細的…

[C#][VB.NET]Isolated Storage 隔離儲存區

 

Dotblogs 的標籤: