C#讀寫檔案總結
轉自:http://www.cnblogs.com/qiantuwuliang/archive/2009/03/12/1409417.html
讀檔案核心程式碼:
寫檔案核心程式碼:
- 使用FileStream讀寫檔案
檔案頭:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
讀檔案核心程式碼:
byte[] byData = new byte[100];
char[] charData = new char[1000];
try
{
FileStream sFile = new FileStream("檔案路徑",FileMode.Open);
sFile.Seek(55, SeekOrigin.Begin);
sFile.Read(byData, 0, 100); //第一個引數是被傳進來的位元組陣列,用以接受FileStream物件中的資料,第2個引數是位元組陣列中開始寫入資料的位置,它通常是0,表示從陣列的開端檔案中向陣列寫資料,最後一個引數規定從檔案讀多少字元.
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
Console.ReadLine();
寫檔案核心程式碼:
FileStream fs = new FileStream(檔案路徑,FileMode.Create);
//獲得位元組陣列
byte [] data =new UTF8Encoding().GetBytes(String);
//開始寫入
fs.Write(data,0,data.Length);
//清空緩衝區、關閉流
fs.Flush();
fs.Close();
- 使用StreamReader和StreamWriter
StreamReader讀取檔案:
StreamReader objReader = new StreamReader(檔案路徑);
string sLine="";
ArrayList LineList = new ArrayList();
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null&&!sLine.Equals(""))
LineList.Add(sLine);
}
objReader.Close();
return LineList;
StreamWriter寫檔案:
FileStream fs = new FileStream(檔案路徑, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write(String);
//清空緩衝區
sw.Flush();
//關閉流
sw.Close();
fs.Close();
相關文章
- C++檔案讀寫總結C++
- c#讀寫ini檔案C#
- 使用C#讀寫ini檔案C#
- 使用C#讀寫xml檔案C#XML
- C#讀取文字檔案和寫文字檔案C#
- C#關於讀寫INI檔案C#
- C# winform中讀寫ini檔案C#ORM
- C#中讀寫INI配置檔案C#
- python檔案操作-讀寫刪除複製總結Python
- C#讀寫xml檔案應用案例C#XML
- C#檔案路徑操作總結
- Python常用配置檔案ini、json、yaml讀寫總結PythonJSONYAML
- 檔案讀寫
- Yaml檔案語法及讀寫小結YAML
- C# Log4net配置檔案 總結C#
- 檔案排版(文字檔案讀寫)
- 檔案的讀寫
- Golang 讀、寫檔案Golang
- keras讀寫檔案Keras
- perl 讀寫檔案
- 檔案讀寫IO
- winform c#寫ini檔案ORMC#
- C#讀取Xml檔案C#XML
- C#讀取Excel方法總結C#Excel
- 「Python」:檔案讀寫Python
- Python——檔案讀寫Python
- Python 讀寫檔案Python
- C++檔案讀寫C++
- 普通檔案的讀寫
- 【Java】讀寫文字檔案Java
- c fopen檔案讀寫
- 讀寫iOS XML檔案iOSXML
- Python讀寫檔案Python
- C++讀寫檔案C++
- VBA建立文字檔案、讀寫文字檔案
- 檔案操作之按照行讀寫檔案
- C#讀取ini配置檔案C#
- c# 圖片檔案讀取C#