namespace file
{
class MyFile
{
string FilePath;
byte[] byData = new byte[100];
public char[] MyData = new char[1000];
public string reslutstr = null;
public MyFile()
{ }
public MyFile(string path)
{
FilePath = path;
}
public void ReadFile1()
{
try
{
FileStream file = new FileStream(FilePath, FileMode.Open);
file.Seek(0, SeekOrigin.Begin);
file.Read(byData, 0, 100); //byData傳進(jìn)來的字節(jié)數(shù)組,用以接受FileStream對象中的數(shù)據(jù),第2個參數(shù)是字節(jié)數(shù)組中開始寫入數(shù)據(jù)的位置,它通常是0,表示從數(shù)組的開端文件中向數(shù)組寫數(shù)據(jù),最后一個參數(shù)規(guī)定從文件讀多少字符.
Decoder d = Encoding.Default.GetDecoder();
d.GetChars(byData, 0, byData.Length, MyData, 0);
//Console.WriteLine(MyData);
foreach (char ch in MyData)
{
reslutstr += ch.ToString();
}
file.Close();
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
}
public void ReadFile2()
{
StreamReader sr = new StreamReader(FilePath, Encoding.Default);
String line;
while ((line = sr.ReadLine()) != null)
{
reslutstr += line;
// Console.WriteLine(line.ToString());
}
}
public void SaveFile1(string savestr)
{
FileStream fs = new FileStream(FilePath, FileMode.Create);
//獲得字節(jié)數(shù)組
byte[] data = System.Text.Encoding.Default.GetBytes(savestr);
//開始寫入
fs.Write(data, 0, data.Length);
//清空緩沖區(qū)、關(guān)閉流
fs.Flush();
fs.Close();
}
public void SaveFile2()
{
FileStream fs = new FileStream(FilePath, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write("Hello World!!!!");
//清空緩沖區(qū)
sw.Flush();
//關(guān)閉流
sw.Close();
fs.Close();
}
}
}
//調(diào)用方法:
MyFile MyFile = new MyFile(Filepath);
string result = null;
// MyFile.SaveFile1(savastr);
MyFile.SaveFile2();
MyFile.ReadFile2();
新聞熱點
疑難解答