日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

读入txt

發布時間:2023/12/1 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 读入txt 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

用C#讀取txt文件的方法

1、使用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();
?
2、使用StreamReader和StreamWriter
?
文件頭:
?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
?
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#讀取.txt文件,常用
StreamReader sr = new StreamReader("TestFile.txt")///StreamReader sr = new StreamReader("TestFile.txt",Encoding.GetEncoding("GB2312"))
///GBK
String line;
while ((line = sr.ReadLine()) != null)
{
?? textBox1 .Text +=ii.ToString ()+" -"+line.ToString()+"\r\n";

}
加入引用:System.IO
StreamReader objReader = new StreamReader("c:\\test.txt");
???? System.IO 命名空間中的對象,尤其是 System.IO.StreamReader 類。

\r\n一般一起用,用來表示鍵盤上的回車鍵.也可只用\n.\t表示鍵盤上的“TAB”鍵。

轉載于:https://www.cnblogs.com/henyihanwobushi/archive/2012/08/15/2640090.html

總結

以上是生活随笔為你收集整理的读入txt的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。