C#的輸入輸出資料流

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   sp   for   

 

     一 .NET Framework 類庫的System.IO 命名空間

      System.IO 命名空間包含允許讀寫檔案和資料流的類型以及提供基本檔案和目錄支援的類型。
      二 C#檔案讀寫之FileStream詳解

  1. (FileStream fs1 = File.Open("c://test.txt", FileMode.Open));

  FileMode.Open 直接用FileStream類開啟檔案c://test.txt"。

  2. (FileStream fs2 = File.Open("c://test.txt", FileMode.Append, FileAccess.Write));

  FileMode.Append,以追加的方式開啟檔案"c://test.txt",將某些內容寫到"c://test.txt"裡。

  3.(FileStream fs3 =File.Open("c://test.txt", FileMode.Truncate, FileAccess.ReadWrite, FileShare.Read)).

  FileMode.Truncate的意思是將檔案開啟清空裡面的內容後再對檔案進行操作。

  4. FileStream MyFileStream1 = new FileStream(@"c:/Testing.txt", FileMode.Create);

  這個方法的意思是建立一個可以讀寫的檔案,並且可以允許其他人讀取檔案的內容。

      三 C#基於流的輸入輸出      C#基於流的輸入輸出.:Stream-通過C# I/O 系統與物理裝置串連起來,也就是平時讀寫的硬碟等物理存貯裝置.流/Stream的方法和屬性有:  

Method/ Properties 描述
void Close() 關閉流
void Flush() 清理流中的內容
int ReadByte() 返回一個整數表示輸入的位元組數,如果沒有資料返回-1
int Read(byte[ ] buf,int offset, int numBytes)

  將numBytes個位元組讀入到byte[ ]的以offset為,起始位置,返回讀入成功的位元組數

Long Seek(long offset,SeekOrigin origin) 將當前位置定位到以origin為初始位置以後的offset處.
void WriteByte(byte b) 將單個位元組寫入到一個輸出資料流.
void Write(byte[ ] buf,int offset, int numBytes) 寫入byte[ ] buf中從offset開始的numBytes個位元組.
bool CanRead 是否可讀
bool CanSeek 是否支援定址
bool CanWrite 是否可以寫入資料
long Length 流的長度
long Position 流的當前位置.

 

  三. 流的繼承結構

   Stream是一個很大類的,在讀寫檔案的時候,可以通過不同的流進行專業的資料讀寫.

 

 

  The FileMode and FileAccess的幾條規則:

 

Value 意義
FileMode.Create 建立檔案,之前存在同名的檔案將被毀掉
FileMode.CreateNew 建立新檔案,這個檔案之前不存在
FileMode.Open 開啟已經存在的檔案
FileMode.OpenOrCreate 開啟檔案如果存在,否則建立新檔案
FileMode.Truncate 開啟以存在的檔案,將它的內容清除掉
FileMode.Append 以追加的形式將資料寫入到檔案的最後

 

  如果在開啟檔案的時候想限制檔案存取權限,那麼可以做如下的構造方法:

  FileStream(string filename, FileMode mode, FileAccess access);

                   檔案名稱       檔案模式       操作模式

Access可以是以下當中的一個值:  FileAccess.Read/  FileAccess.Write/  FileAccess.ReadWrite;  FileStreamfs=new FileStream(“c://tab.txt”,FileMode.OpenOrCreate,FileAccess.Read);C#中結合Post發送的Stream與Byte Array的操作似乎資料很少.下面是我這幾天的研究成果.功能是將同檔案夾下的a.jpg複製產生b.jpg.代碼如下:byteArray.aspx.csusing System;using System.IO;using System.Data;using System.Drawing;using System.Drawing.Imaging;using System.Net;/*@Author:frankSite:www.2solo.cnDate:2008.02.20Info:C#複製圖片,流與byteArray的應用,產生圖片部分*/namespace bArray {   public partial class imgHandler : System.Web.UI.Page      {         protected void Page_Load(object sender, EventArgs e)          {             try             {                 Stream sin = Page.Request.InputStream;                 System.Drawing.Image img = System.Drawing.Bitmap.FromStream(sin);                 Bitmap bmp = new Bitmap(img);                 MemoryStream bmpStream = new MemoryStream();                 bmp.Save(bmpStream, System.Drawing.Imaging.ImageFormat.Jpeg);                 FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath("b.jpg"), FileMode.Create);                 bmpStream.WriteTo(fs);                 bmpStream.Close();                 fs.Close();                 bmpStream.Dispose();                 fs.Dispose();                 Response.Write("成功");             }             catch             {                 Response.Write("失敗");             }         }     } } gopost.aspx.csusing System;using System.IO;using System.Drawing; using System.Drawing.Imaging;using System.Net; using System.Text; /*@ Author:frankSite:www.2solo.cn Date:2008.02.20info:C#複製圖片,流與byteArray的應用,提交圖片部分 */ namespace gopost{     public partial class postHandler : System.Web.UI.Page     {        protected void Page_Load(object sender, EventArgs e)         {           postImage();         }       private void postImage()        {             try             {                 HttpWebRequest request;                 string imgUrl = System.Web.HttpContext.Current.Server.MapPath("a.jpg");                 request = (HttpWebRequest)HttpWebRequest.Create(http://localhost/byteArray/byteArray.aspx);                 request.KeepAlive = true;                 request.Method = "POST";                 byte[] byteArray = CvtImgBArr((System.Drawing.Image)new Bitmap(@imgUrl), ImageFormat.Jpeg);                 request.ContentType = "image/JPEG";                 request.ContentLength = byteArray.Length;                Stream newStream = request.GetRequestStream();                newStream.Write(byteArray, 0, byteArray.Length);                 newStream.Close();                 Response.Write("複製圖片成功");             }             catch             {                Response.Write("複製圖片失敗");             }        }        private static byte[] CvtImgBArr(System.Drawing.Image imageToConvert, ImageFormat formatOfImage)        {            byte[] imArr;             try             {                 using (MemoryStream myms = new MemoryStream())                 {                    imageToConvert.Save(myms, formatOfImage);                    imArr = myms.ToArray();                 }             }            catch (Exception) { throw; }             return imArr;         }    } }

相對來說,byte Array在Html表單中的應用可能一直被忽視,但是正確的應用byte Array可以大大的最佳化程式,並做出一些意想不到的效果來。

 

C# Stream 和 byte[] 之間的轉換 /* - - - - - - - - - - - - - - - - - - - - - - - -   * Stream 和 byte[] 之間的轉換  * - - - - - - - - - - - - - - - - - - - - - - - */ /// <summary> /// 將 Stream 轉成 byte[] /// </summary> public byte[] StreamToBytes(Stream stream) {     byte[] bytes = new byte[stream.Length];     stream.Read(bytes, 0, bytes.Length);     // 設定當前流的位置為流的開始     stream.Seek(0, SeekOrigin.Begin);     return bytes; } /// <summary> /// 將 byte[] 轉成 Stream /// </summary> public Stream BytesToStream(byte[] bytes) {     Stream stream = new MemoryStream(bytes);     return stream; } /* - - - - - - - - - - - - - - - - - - - - - - - -   * Stream 和 檔案之間的轉換  * - - - - - - - - - - - - - - - - - - - - - - - */ /// <summary> /// 將 Stream 寫入檔案 /// </summary> public void StreamToFile(Stream stream,string fileName) {     // 把 Stream 轉換成 byte[]     byte[] bytes = new byte[stream.Length];     stream.Read(bytes, 0, bytes.Length);     // 設定當前流的位置為流的開始     stream.Seek(0, SeekOrigin.Begin);     // 把 byte[] 寫入檔案     FileStream fs = new FileStream(fileName, FileMode.Create);     BinaryWriter bw = new BinaryWriter(fs);     bw.Write(bytes);     bw.Close();     fs.Close(); } /// <summary> /// 從檔案讀取 Stream /// </summary> public Stream FileToStream(string fileName) {                 // 開啟檔案     FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);     // 讀取檔案的 byte[]     byte[] bytes = new byte[fileStream.Length];     fileStream.Read(bytes, 0, bytes.Length);     fileStream.Close();     // 把 byte[] 轉換成 Stream     Stream stream = new MemoryStream(bytes);     return stream; } 另外,XML的一個應用是序列化,要用到把字串轉化成byte數組,方法:     byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(XmlContent); 相對的,把byte數組轉化為字串的方法則為:  string XmlContent = System.Text.UTFEncoding.UTF8.GetString(bytes);從字串到流Streambyte[] buffer = System.Text.Encoding.Unicode.GetBytes("faint"); MemoryStream stream = new MemoryStream(buffer);MemoryStream ms = new MemoryStream(System.Text.Encoding.Default.GetBytes(AObjStr));

 

 

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.