zoukankan      html  css  js  c++  java
  • C# Byte[]数组读取和写入文件

    这个项目我用的是asp.net构建的,代码如下

     1  protected void ByteToString_Click(object sender, EventArgs e)
     2         {
     3 
     4 
     5             string content = this.txtContent.Text.ToString();
     6 
     7             if (string.IsNullOrEmpty(content))
     8             {
     9                 return;
    10             }
    11 
    12             //string 转为byte数组
    13             byte[] array = Encoding.UTF8.GetBytes(content);
    14 
    15             //将byte数组转为string
    16             string result = Encoding.UTF8.GetString(array);
    17 
    18 
    19             Response.Write(result);
    20 
    21 
    22         }
    23         //利用byte[]数组写入文件
    24         protected void writerFile_Click(object sender, EventArgs e)
    25         {
    26 
    27             string content = this.txtContent.Text.ToString();
    28 
    29             if (string.IsNullOrEmpty(content))
    30             {
    31                 return;
    32             }
    33 
    34             //将string转为byte数组
    35             byte[] array = Encoding.UTF8.GetBytes(content);
    36 
    37             string path = Server.MapPath("/test.txt");
    38             //创建一个文件流
    39             FileStream fs = new FileStream(path, FileMode.Create);
    40 
    41             //将byte数组写入文件中
    42             fs.Write(array, 0, array.Length);
    43             //所有流类型都要关闭流,否则会出现内存泄露问题
    44             fs.Close();
    45 
    46             Response.Write("保存文件成功");
    47 
    48 
    49         }
    50         //利用byte[]数组读取文件
    51         protected void readFile_Click(object sender, EventArgs e)
    52         {
    53             string path = Server.MapPath("/test.txt");
    54 
    55             FileStream fs = new FileStream(path, FileMode.Open);
    56 
    57             //获取文件大小
    58             long size = fs.Length;
    59 
    60             byte[] array = new byte[size];
    61 
    62             //将文件读到byte数组中
    63             fs.Read(array, 0, array.Length);
    64 
    65             fs.Close();
    66 
    67             //将byte数组转为string
    68             string result = Encoding.UTF8.GetString(array);
    69 
    70 
    71             Response.Write(result);
    72 
    73             
    74 
    75         }
  • 相关阅读:
    HFUT 1356.转啊转(安徽省2016“京胜杯”程序设计大赛 E)
    HFUT 1354.砝码称重(安徽省2016“京胜杯”程序设计大赛 A)
    AOJ 331.汉诺塔
    AOJ 763.过河卒
    AOJ 762.分数数列
    AOJ 761.Fibonacci序列
    AOJ 760.尾数相等的数
    POJ 1035.Spell checker
    POJ 2299.Ultra-QuickSort
    POJ 2503.Babelfish
  • 原文地址:https://www.cnblogs.com/ouyangfu/p/4825448.html
Copyright © 2011-2022 走看看