asp.net中的记忆盲区

 <1>  连接数据库  用read方法取出数据   在web.config取出连接字符串   

        string sqlconn = ConfigurationManager.ConnectionStrings["db_showHouseConnectionString"].ToString();
        SqlConnection   conn=new SqlConnection (sqlconn );
        SqlCommand com = new SqlCommand("select  *   from  film", conn);
        conn.Open();
        SqlDataReader sql = com.ExecuteReader(CommandBehavior.CloseConnection);//当读取完毕数据时同时关闭数据库连接
        GridView1.DataSource = sql;
        GridView1.DataBind();
  <2>   GridView中有一个属性能够实现局部刷新   EnableSortingAndPagingCallbacks="True"
  <3>   ctrl+shift+a为添加新的一个页面的快捷键
  <4>   在Cmd中添加参数时能够可以根据数据类型自动添加相应的参数
            com.Parameters.AddWithValue("name", Name);
                 name为自己起的的名字
                 Name为实参数
         此处一般应用于存储过程中的应用
  <5>比较好的数据库记录删除方式
       protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
                string sqlconn = ConfigurationManager.ConnectionStrings["db_showHouseConnectionString"].ToString();
                SqlConnection conn = new SqlConnection(sqlconn);
                SqlCommand com = new SqlCommand("select  *   from  film", conn);
                SqlDataAdapter sda = new SqlDataAdapter(com);
                SqlCommandBuilder scmd = new SqlCommandBuilder(sda);//此句很重要
              
//DataTable dt = new DataTable();
                DataSet sa = new DataSet();
                sda.Fill(sa, "dt2");
                sa.Tables["dt2"].DefaultView.Delete(e.RowIndex);     
                int rows = sda.Update(sa, "dt2");
                Response.Write("成功");
              
     }
  <6>将数据集放入到catche中,,缓存的作用用来暂时存储数据,减少与服务器的链接

          DataSet ds =(DataSet) Cache.Get("cache_Name");//在cache中取出数据集然后转化使用
            if (ds == null)
           {
            string sqlconn = ConfigurationManager.ConnectionStrings["db_showHouseConnectionString"].ToString();
            SqlConnection conn = new SqlConnection(sqlconn);
            SqlCommand com = new SqlCommand("select  *   from  film", conn);
            SqlDataAdapter sda = new SqlDataAdapter(com);
            DataSet sa = new DataSet();
            sda.Fill(sa, "dt");

            //*    将dataset放入到页面缓存中去,以便能及时的取出信息,增加客户浏览的速度    */
            sa.ExtendedProperties.Add("dt2_name", DateTime.Now.ToLongTimeString());
            Cache.Insert("cache_Name", sa, null, DateTime.Now.AddMinutes(2), TimeSpan.Zero);
            //____________________________________________________________________________________*//



              GridView1.DataSource = sa.Tables["dt"].DefaultView;
              GridView1.DataBind();
          }

    Cache.Remove("cache_Name");//将数据集从缓存中移除掉

  <7>  标记出当前网站所在的目录 Response.Write(Server .MapPath ("."));
  <8>  所有的文件在计算机中都能将其转化成二进制的格式的流媒体,将其存入到数据库中或者将其存入到xml中的文件中,,应用的时候可以将其在读取出来,然后转化成相应的文件

    ///<summary>
   
/// 将文件转化成二进制的字符串
   
///</summary>
   
///<param name="Path">文件存储的路径</param>
   
///<returns></returns>
    public static string Create_File_Tobit(string Path)
    {
        FileStream Fs = new FileStream(Path, FileMode.Open, FileAccess.Read);
        //创建fs实例读取数据流
        int Lenth = Convert.ToInt32(Fs.Length);
        //得到数据的大小
        Byte[] liu = new byte[Lenth];
        //创建一个内存缓存区
        BinaryReader BR = new BinaryReader(Fs);
        //申请一个BR用了完成数据流二进制的转化
       
            BR.Read(liu, 0, Lenth);
      
        string Data_liu = Convert.ToBase64String(liu);
        BR.Close();
        Fs.Close();
        return Data_liu;

    }



    ///<summary>
   
/// 将二进制文件存为文件
   
///</summary>
   
///<param name="Path">存入文件的路径</param>
   
///<param name="Shu_Ju">二进制格式文件字符</param>
    public static void bit_To_File(string Path, string Shu_Ju)
    {
        FileStream Fs = new FileStream(Path, FileMode.Create, FileAccess.Write);//此为创建一个fileStream实例,格式为创建,写入
        BinaryWriter BW = new BinaryWriter(Fs);//二进制文件写入实例
        BW.Write(Convert.FromBase64String(Shu_Ju));//将二进制格式的流媒体写入文件
        BW.Close();
        Fs.Close();
    }





    以上两个方法中,方法1实现的是将传入的路径中的文件读取成二进制流媒体,然后转化成相应的字符串。
    方法2实现的是将传入的二进制的格式的文件存入到传来的地址中,引用为:
        string a = Du_Bite.Create_File_Tobit(Server.MapPath("qq.jpg"));//将已有的图片的文件读出为二进制文件
        Du_Bite.bit_To_File(Server.MapPath("ddd.jpg"), a);//将二进制的文件存入到文件中命名为ddd.jpg
   <9>将图片文件存入到数据库中,然后读取出来
       1、数据库定义
                         三个字段 id   int    ; gid  uniqueidentifier   ;img    image   ;表名为xml

                        uniqueidentifier:为数据类型,全球唯一标识,一般接受guid定义的类型
                        image:为图片的类型
       2、页面中放一个上传文件的控件,用来上传图片
       3、存入数据库的代码如下:
         if (FileUpload1.HasFile)
          {
            Guid gid = Guid.NewGuid();  //此句为表示出全球唯一的标识代码编号,,据称为全球不会重复
            string sqlconn = ConfigurationManager.ConnectionStrings["db_showHouseConnectionString"].ToString();
            SqlConnection conn = new SqlConnection(sqlconn);
            SqlCommand com = new SqlCommand("INSERT INTO Xml (guid, img) VALUES (@guid,@img)", conn);
            com.Parameters.Add("@guid", SqlDbType.UniqueIdentifier).Value = gid;
            com.Parameters.Add("@img", SqlDbType.Image).Value = FileUpload1.FileBytes;   //将上传的文件转换成流媒体,,然后放入到数据库img中。。。。。。此处只能用这种方法存入数据

            conn.Open();
            com.ExecuteNonQuery();
            conn.Close();
            Session["gid"] = gid;
            Response.Write("成功");
         }
        else
        {
            Response.Write("请上传文件!");
        }
      4、将图片文件从数据库中取出,,然后写入到界面中
        string sqlconn = ConfigurationManager.ConnectionStrings["db_showHouseConnectionString"].ToString();
        SqlConnection conn = new SqlConnection(sqlconn);
        SqlCommand com = new SqlCommand("select img  from  xml  where  guid='"+Session ["gid"].ToString ()+"'", conn);
        conn.Open();
        byte[] liu = (byte[])com.ExecuteScalar();   //将流媒体读出然后存入到计算机缓存中

        conn.Close();
        Response.OutputStream.Write(liu, 0, liu.Length);    //将流媒体写入到页面中,,,记住这种方法
        Response.End();    //读取结束
9》 下面这个实例是将图片的文件写入到xml文件中。。。此处是一个难点,要牢牢记住

    <1> 这个函数实现xml文件的创建以及写入
               这个函数是通过的方法调用
                                                     string Xml_Path = Server.MapPath("~/App_Data/img.xml");
                                                     Guid gid = Guid.NewGuid();
                                                     Session["gid"] = gid.ToString();
                                                     Bite_To_Xml.File_To_Xml(FileUpload1, Xml_Path, gid.ToString ());
                                                     Response.Write(gid.ToString() + "img.xml   已经成功创建");



           public static void File_To_Xml(FileUpload fu, string Xml_Path, string Gid)
              {    //fu为调用此函数的一个上传控件   Xml_Path 这个是要保存的xml文件的地址  Gid  是要保存的编号
                 if (fu.HasFile)
                      {
                               string File_Path = fu.FileName.ToString();
                               int File_Lenth = fu.PostedFile.ContentLength;   //得到上传图片的大小

                               try
                                    {
                                         Byte[] bit_Array = new byte[File_Lenth];
                                         Stream streamobj = fu.PostedFile.InputStream;//将上传的文件转化成流媒体
                                                 streamobj.Read(bit_Array, 0, File_Lenth);//将文件写入到内存中
                                         /* 以下是建立新的xml文件 ,以方便将流媒体存入到xml文件中  */
                                        XmlDocument xdom = new XmlDocument();
                                        //声明一个xml文件
                               if (!File.Exists(Xml_Path))
                                    {//判断文件是否存在,如果不存在的时候将新建一个xml文件
                                         XmlDeclaration sml_Title = xdom.CreateXmlDeclaration("1.0", "utf-8", null);
                                         xdom.AppendChild(sml_Title);
                                    //创建一行文档的表头声明
                                    XmlElement Root = xdom.CreateElement("File");
                                    xdom.AppendChild(Root);
                                    //创建根节点                  这地方要记住的是每一个子节点都传承与父节点之下,,就是说当这个节点是上面一个节点的子节点的时候就必须使用上一个  //节点的实例创建例如:  xdom.AppendChild(Root);;——————》 Root.AppendChild(Rootlement);

                                    XmlElement Rootlement = xdom.CreateElement("Image");
                                    Root.AppendChild(Rootlement);
                                    //创建父节点

                                    XmlElement ChildElement = xdom.CreateElement("Guid");
                                    ChildElement.InnerText = Gid;
                                    Rootlement.AppendChild(ChildElement);
                                    //将guid传来的值存入xml的子节点

                                    XmlElement ChildElement2 = xdom.CreateElement("Size");
                                    ChildElement2.InnerText = File_Lenth.ToString();
                                    Rootlement.AppendChild(ChildElement2);
                                    //将文件的大小存入xml文件中

                                    XmlElement ChildElementimgDate = xdom.CreateElement("imgDate");
                                    ChildElementimgDate.InnerText = Convert.ToBase64String(bit_Array);  //将媒体流转化成字符写入到xml中
                                    Rootlement.AppendChild(ChildElementimgDate);
                 
                                    //将流媒体写入到xml文件中
                                    xdom.Save(Xml_Path);
                                    }
                              else
                                    {
                                        xdom.Load(Xml_Path);
                                       //读取xml文件到xdom中
                                       XmlNode root = xdom.SelectSingleNode("File");
                                       //读取到xml中相应的节点,然后标志处此行来


                                       XmlElement Rootelement = xdom.CreateElement("Image");
                                       root.AppendChild(Rootelement);
                                       //创建父节点
                                       XmlElement ChildElement = xdom.CreateElement("Guid");
                                       ChildElement.InnerText = Gid;
                                       Rootelement.AppendChild(ChildElement);

                                       //将guid传来的值存入xml的子节点
                                       XmlElement ChildElement2 = xdom.CreateElement("Size");
                                       ChildElement2.InnerText = File_Lenth.ToString();
                                       Rootelement.AppendChild(ChildElement2);
                                       //将文件的大小存入xml文件中

                                       XmlElement ChildElementimgDate = xdom.CreateElement("imgDate");
                                       ChildElementimgDate.InnerText = Convert.ToBase64String(bit_Array);
                                       Rootelement.AppendChild(ChildElementimgDate);

                                      //将流媒体写入到xml文件中
                                      xdom.Save(Xml_Path);
                                   }
                          }
                         catch (Exception oe)
                         {
                             throw (oe);
                         }
                    }

              }
     <2> 下面这个函数实现xml文件的读取工作,从xml文件中读取出来。。然后写入到页面中
                        protected void Button4_Click(object sender, EventArgs e)
                        {
                                 XmlDocument Xml = new XmlDocument();
                                 Xml.Load(Server.MapPath("App_Data/img.xml"));//此处为新实例化的一个xml文件

                                 XmlNodeList XNL = Xml.SelectSingleNode("//Image[Guid='" + Session["gid"].ToString () + "']").ChildNodes;  //将xml文件读取出来标志此节点以下的所有的节点集合赋值给XNL

                                 for(int i=0;i<XNL .Count ;i++)
                                 {
                                          string   imgdata=XNL.Item (2).InnerText ;
                                          Response.OutputStream.Write(Convert.FromBase64String(imgdata), 0, imgdata.Length);  //将文件流写入到页面中
                                          Response.End();  //结束文件的写入工作
                                 }
                         }
10》 怎样将图片的二进制媒体流,在页面中显示图片的同时保证控制的图片的大小的控制

                1. 添加一个新的aspx 命名 为 image.aspx;

                2. 在image.aspx里 的 page_load里 写这句话:Response.BinaWrite(byte[]buffer); 输出buffer中的二进制图像流,将图片显示到这个页面中。

                3. 然后把你的image控件的  Imageurl  = "image.aspx";

                  最终 你的 image控件 就 能显示 二进制流图像了。

                在image.aspx中显示的图片,在别的页面中调用此页面就可以。

原文地址:https://www.cnblogs.com/zuoguanglin/p/2408946.html