顯示具有 stream 標籤的文章。 顯示所有文章
顯示具有 stream 標籤的文章。 顯示所有文章

2014年5月9日 星期五

[C#] txt or csv檔案 多次重新讀取

通常我們讀檔都會使用StreamReader,但往往只能讀一次,無法從頭開始。

最基本的如下:

try
{
     using (StreamReader SR = new StreamReader(路徑)
    {
          string Line;

           while ((Line = SR.ReadLine()) != null) //一次讀一行
           {
                  string[] ReadLine_Array = Line.Split(',');//csv檔用逗號做分隔
                  //這邊可以處理文件
           }
     }
 }
 catch (IOException)
 { }
 catch (NullReferenceException)
 { }
 catch (FormatException)
 { }

在using裡面讀完一次就無法再從頭讀起,因此我們需要增加

StreamReader.ReadToEnd();//標頭拉到尾
StreamReader.BaseStream.Seek(0, SeekOrigin.Begin);//標頭重新回到最開始

增加以後就可以讓 檔案再次從頭讀起!

End

2014年2月11日 星期二

[C#/Serialize] 簡易版本-Serailize/Deserialize

上一篇序列化/反序列化比較難,這次寫一點簡單的。

首先一樣先建一個類別庫(新增專案->類別庫)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Solar_stucture
{
    [Serializable]
    public class Solar_read
    {
        public byte Adress = 0;
        public byte Function_code = 0;
        public byte Byte_count = 0;
    }
}

然後建製(F9) 會產生錯誤,很正常。但不是錯誤。(在Debug資料夾內會有.dll檔)

接著,開個新的專案。然後  專案->加入參考...(瀏覽->選剛剛產生的dll檔)

在主程式(或任何你想要加的地方)加入

Solar_read Read_protocol = new Solar_read();

然後使用Read_protocol.Adress,你會發現可以使用!!

沒錯,就把東西存進去(型別要對)

都加完了以後,開始寫入檔案。

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("Read Protocol.dat", FileMode.Create, FileAccess.Write,       FileShare.Read);
            formatter.Serialize(stream, Read_protocol);
            stream.Close();

記得dll檔那邊要有[Serializable]不然這邊執行上會出現serialize的異常。序列化到此結束!


基本的反序列化也十分簡單:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Solar_stucture;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace SolarControl_Front
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(序列化存的檔案路徑, FileMode.Open, FileAccess.Read, FileShare.Read);
            Solar_read read = (Solar_read)formatter.Deserialize(stream);
            MessageBox.Show(read.Adress.ToString());
            stream.Close();

        }
    }
}

一樣的東西,只是變成Deserialize(Stream stream),接的格式是用你所創建的Class格式喔!

MessageBox只是確認有弄對而已。 Over