zoukankan      html  css  js  c++  java
  • C#的输入输出流

       一 .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.cs
    
    using System;
    
    using System.IO;
    
    using System.Data;
    
    using System.Drawing;
    
    using System.Drawing.Imaging;
    
    using System.Net;
    
    /*@
    
    Author:frank
    
    Site:www.2solo.cn
    
    Date:2008.02.20
    
    Info: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.cs
    
    using System;
    
    using System.IO;
    
    using System.Drawing; 
    using System.Drawing.Imaging;
    
    using System.Net; 
    using System.Text; 
    /*@ 
    Author:frank
    
    Site:www.2solo.cn 
    Date:2008.02.20
    
    info: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);
    
    从字符串到流Stream
    
    byte[] buffer = System.Text.Encoding.Unicode.GetBytes("faint"); 
    MemoryStream stream = new MemoryStream(buffer);
    
    MemoryStream ms = new MemoryStream(System.Text.Encoding.Default.GetBytes(AObjStr));
  • 相关阅读:
    Problem 1014 xxx游戏 暴力+拓扑排序
    Codeforces Beta Round #10 D. LCIS
    HDU 1423 Greatest Common Increasing Subsequence LCIS
    Codeforces Round #349 (Div. 1) A. Reberland Linguistics dp
    BZOJ 3875: [Ahoi2014]骑士游戏 dp+spfa
    Codeforces Round #360 (Div. 2) E. The Values You Can Make 01背包
    Codeforces Round #360 (Div. 2) D. Remainders Game 中国剩余定理
    UVALive 4872 Underground Cables 最小生成树
    POJ 1182 食物链 并查集
    山东省第六届ACM省赛
  • 原文地址:https://www.cnblogs.com/9999w/p/4173110.html
Copyright © 2011-2022 走看看