1. 程式人生 > >C#使用FileStream檔案讀寫

C#使用FileStream檔案讀寫

最近學習C#的過程中,要讀寫檔案,自己使用FileStream類寫了以下小段程式碼,一來自己學習練手,二來將這段程式碼貼出來,供想學習C#的朋友學習。

一.C# 程式碼

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

namespace FileReader
{
    class Program
    {
        static void Main(string[] args)
        {
            //////////////////////////////////////////////////////////////////////////
            //寫檔案
            WriteByteToFile();
            //////////////////////////////////////////////////////////////////////////
            //讀取檔案
            ReadByteFromFile();

        }

        private static void ReadByteFromFile()
        {
            try
            {
                byte[] array = new byte[100];
                FileStream file = new FileStream("wang.bin", FileMode.Open);
                file.Seek(0, SeekOrigin.Begin);


                if (file.CanRead)
                {
                    file.Read(array, 0, 100);
                }
                Console.WriteLine(Encoding.Default.GetString(array));
                file.Close();
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
            

        }
        private static void WriteByteToFile()
        {
            try
            {
                string teststr = "This is C# Language Stream Test";
                byte[] array = new byte[teststr.Length+1];

                for (int i = 0; i < teststr.Length; i++)
                {
                    array[i] = (byte)teststr[i];
                }
                //////////////////////////////////////////////////////////////////////////
                FileStream file = new FileStream("wang.bin", FileMode.Create);
                long len = file.Length;
                file.Seek(len, SeekOrigin.Current);
                file.Write(array, 0, teststr.Length+1);
                file.Close();
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
    }
}

二.寫檔案結果

三.檔案讀取結果