C# 流

來源:互聯網
上載者:User

標籤:字串   利用   default   http   eric   string   分享   格式   code   

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO;//流namespace Stream{    class Program    {        static void Main(string[] args)        {            Stream2();            Console.ReadKey();        }        static void Stream1()        {            string filePath = "D:\\test.txt";            //利用File.Open建立一個FileStream實體            using (FileStream filestream = File.Open(filePath, FileMode.Open))            {                //定義字串                string msg = "hello world";//string msg =Console.ReadLine();                //將字串轉化為位元組資料                byte[] msgAsByteArray = Encoding.Default.GetBytes(msg);                Console.WriteLine("開始寫入到檔案中{0}", msg);                //將位元組資料寫入到流中                filestream.Write(msgAsByteArray, 0, msgAsByteArray.Length);                //重設流中的位置                filestream.Seek(0, SeekOrigin.Begin);                Console.WriteLine("寫入檔案中的資料為:");                //定義位元組數組                byte[] bytesFormFile = new byte[msgAsByteArray.Length];                //從流中讀取到位元組資料                filestream.Read(bytesFormFile, 0, msgAsByteArray.Length);                Console.WriteLine(Encoding.Default.GetString(bytesFormFile));            }        }        /// <summary>        /// StreamWriter與StreamReader        /// </summary>        static void Stream2()        {            string filePath = "D:\\test.txt";            using (FileStream filestream = File.Open(filePath, FileMode.Open))            {                //定義字串                string msg = "hello world(你好)";//string msg =Console.ReadLine();                //建立StreamWriter對象System.Text.Encoding.Default:編碼格式                StreamWriter streamwriter = new StreamWriter(filestream,System.Text.Encoding.Default);                Console.WriteLine("開始寫入{0}到檔案中", msg);                streamwriter.Write(msg);                //建立StreamReader對象                StreamReader streamreader = new StreamReader(filestream, Encoding.Default);                //這裡將讀不到資料,因為還未寫入完成                Console.WriteLine("寫入到檔案中資料為{0}", streamreader.ReadToEnd());                //關閉                streamwriter.Close();                streamreader.Close();            }        }    }}

Stream繼承結構:

 

C# 流

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.