C#FileStrea讀寫

菜鸟的奋斗军發表於2024-12-05
      //FileStream 操作位元組的
      //StreamReader和StreamWriter 操作字元的
      FileStream fsRead = new FileStream(@"C:\Users\admin\Desktop\av.txt", FileMode.OpenOrCreate, FileAccess.Read);
      byte[] buffer = new byte[1024 * 1024 * 5];
      fsRead.Read(buffer, 0, buffer.Length);
      //返回本次實際讀取到的有效位元組數
      int r = fsRead.Read(buffer, 0, buffer.Length);
      //將位元組陣列中每一個元素按照指定的編碼格式解成字串
      string s = Encoding.Default.GetString(buffer,0,r);
      //關閉流
      fsRead.Close();
      //釋放流所佔用的資源
      fsRead.Dispose();
      Console.WriteLine(s);
      Console.ReadKey();


      //使用FileStream來寫入資料
      using (FileStream fswrite = new FileStream(@"C:\Users\admin\Desktop\av.txt", FileMode.OpenOrCreate, FileAccess.Write))
      {

          string str = "看我有沒有把你覆蓋掉";
          byte[] buff = Encoding.Default.GetBytes(str);
          fswrite.Write(buff, 0, buff.Length);
          
      
      
      }

      Console.WriteLine("寫入成功");
      Console.ReadKey();