c#FileStream簡単な応用と文字変換
3756 ワード
//
byte[] bt1 = new byte[100];
char[] chars1 = new char[100];
string strs = string.Empty;
chars1 = System.Text.Encoding.UTF8.GetChars(bt1);//byte[] char[]
Decoder dc1 = Encoding.UTF8.GetDecoder();
dc.GetChars(bt1, 0, bt1.Length, chars, 0);//byte[] char[]
chars1 = strs.ToArray();//string char[]
bt1 = System.Text.Encoding.UTF8.GetBytes(strs);//string byte[]
strs = new string(chars);//char[] string
strs = System.Text.Encoding.UTF8.GetString(bt1);//byte[] string
bt1 = System.Text.Encoding.UTF8.GetBytes(chars1);//char[] byte[]
Encoder en = Encoding.UTF8.GetEncoder();
en.GetBytes(chars, 0, chars.Length, bt1, 0, true);//char[] byte[]
//FileStream StreamReader StreamWriter//fs.Position = fs.Length;//書き込み先をテキスト末尾に設定する方法1;//fs.Seek(0, SeekOrigin.End);//書き込み位置をテキスト末に設定する方法2;
using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string path = System.Environment.CurrentDirectory + "\\test.txt";
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.textBox1.Text))
{
MessageBox.Show(" , ");
}
else
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Position = fs.Length;// 1;
//fs.Seek(0, SeekOrigin.End);// 2;
//// StreamWriter
//using (StreamWriter sw = new StreamWriter(fs))
//{
// sw.WriteLine(this.textBox1.Text.ToString());
// sw.Flush();
// sw.Close();
// fs.Close();
//}
// byte[]
try
{
//char[] byte[] 1
Encoder en = Encoding.UTF8.GetEncoder();//write
byte[] bt1 = new byte[this.textBox1.Text.ToArray().Length];
char[] chars = this.textBox1.Text.ToArray();
en.GetBytes(chars, 0, chars.Length, bt1,0, true);
fs.Write(bt1, 0, bt1.Length);
////char[] byte[] 2
//byte[] bt = Encoding.UTF8.GetBytes(this.textBox1.Text.ToString());
//fs.Write(bt, 0, bt.Length);
fs.Flush();
fs.Close();
}
catch (Exception)
{
throw;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//StreamReader sr= new StreamReader(path)
//using (StreamReader sr= new StreamReader(fs))
//{
// string temp = sr.ReadLine();
// while (temp!=null)
// {
// this.textBox1.AppendText(temp+"\r
");
// temp = sr.ReadLine();
// }
// sr.Close();
//}
//byte[] char[] 1
byte[] bt = new byte[100];
fs.Read(bt,0,100);
////byte[] char[] 1
char[] chars = new char[100];
Decoder dc = Encoding.UTF8.GetDecoder();
dc.GetChars(bt, 0, bt.Length, chars, 0);
////byte[] char[] 2
//char[] chars = Encoding.UTF8.GetChars(bt);
////char[] string new string(chars)
////string char[] string.ToArray();
this.textBox1.AppendText(new string(chars));
}
}
}