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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

C#文本文件操作

發布時間:2023/11/27 生活经验 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#文本文件操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如何向現有文件中添加文本
using?System; using?System.IO;class?Test? {public?static?void?Main()?{//?Create?an?instance?of?StreamWriter?to?write?text?to?a?file.//?The?using?statement?also?closes?the?StreamWriter.using?(StreamWriter?sw?=?new?StreamWriter("TestFile.txt"))?{//?Add?some?text?to?the?file.sw.Write("This?is?the?");sw.WriteLine("header?for?the?file.");sw.WriteLine("-------------------");//?Arbitrary?objects?can?also?be?written?to?the?file.sw.Write("The?date?is:?");sw.WriteLine(DateTime.Now);}} }




如何創建一個新文本文件并向其中寫入一個字符串。WriteAllText方法可提供類似的功能。
using?System;
using?System.IO;
public?class?TextToFile?
{private?const?string?FILE_NAME?=?"MyFile.txt";public?static?void?Main(String[]?args)?{if?(File.Exists(FILE_NAME))?{Console.WriteLine("{0}?already?exists.",?FILE_NAME);return;}using?(StreamWriter?sw?=?File.CreateText(FILE_NAME)){sw.WriteLine?("This?is?my?file.");sw.WriteLine?("I?can?write?ints?{0}?or?floats?{1},?and?so?on.",?1,?4.2);sw.Close();}}
}
如何從文本文件中讀取文本
using?System;
using?System.IO;class?Test?
{public?static?void?Main()?{try?{//?Create?an?instance?of?StreamReader?to?read?from?a?file.//?The?using?statement?also?closes?the?StreamReader.using?(StreamReader?sr?=?new?StreamReader("TestFile.txt"))?{String?line;//?Read?and?display?lines?from?the?file?until?the?end?of?//?the?file?is?reached.while?((line?=?sr.ReadLine())?!=?null)?{Console.WriteLine(line);}}}catch?(Exception?e)?{//?Let?the?user?know?what?went?wrong.Console.WriteLine("The?file?could?not?be?read:");Console.WriteLine(e.Message);}}
}
在檢測到文件結尾時向您發出通知。通過使用?ReadAll或?ReadAllText方法也可以實現此功能。
using?System;
using?System.IO;
public?class?TextFromFile?
{private?const?string?FILE_NAME?=?"MyFile.txt";public?static?void?Main(String[]?args)?{if?(!File.Exists(FILE_NAME))?{Console.WriteLine("{0}?does?not?exist.",?FILE_NAME);return;}using?(StreamReader?sr?=?File.OpenText(FILE_NAME)){String?input;while?((input=sr.ReadLine())!=null)?{Console.WriteLine(input);}Console.WriteLine?("The?end?of?the?stream?has?been?reached.");sr.Close();}}
?

總結

以上是生活随笔為你收集整理的C#文本文件操作的全部內容,希望文章能夠幫你解決所遇到的問題。

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