C# 文件操作

一、转UTF-8

1、byte 转 char

Decoder d = Encoding.UTF8.GetDecoder();

d.GetChars(byData, 0, byData.Length, charData, 0);

2、char 转 byte

Encoder e = Encoding.UTF8.GetEncoder();

e.GetBytes(charData, 0, charData.Length, byData,0, true);

3、string 转 char[]

charData = str.ToCharArray();

二、FileStream与StreamWriter、StreamReader对象

FileStream 实现对文件的读写,操作的是字节数组;

 string path = "test.txt";
            try
            {
                //Initializes a new instance of the FileStream class  
                FileStream filestream = File.Create(path);
                //FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
                //write string into file.
                String str = Console.ReadLine(); 
                str = "you input :" + str;
                char[] charArr = str.ToCharArray();
                byte[] byteArr = new byte[charArr.Length];
                Encoder encoder = Encoding.UTF8.GetEncoder();
                encoder.GetBytes(charArr, 0, charArr.Length, byteArr, 0, true);
                filestream.Seek(0, SeekOrigin.Begin);
                filestream.Write(byteArr, 0, byteArr.Length);

                //read string from file
                charArr = new char[200];
                byteArr = new byte[200];
                String outstr = "";
                filestream.Seek(0, SeekOrigin.Begin);
                while (filestream.Read(byteArr, 0, byteArr.Length) > 0)
                {
                    Decoder decoder = Encoding.UTF8.GetDecoder();
                    decoder.GetChars(byteArr, 0, byteArr.Length, charArr, 0);
                    outstr += new String(charArr);
                }
                Console.WriteLine(outstr);

                filestream.Close();

            }
            catch (System.Exception ex)
            {
                Console.WriteLine("An IO Exception has been thrown!");
            }


StreamWriter、StreamReader类允许对字符和字符串进行操作。

string path = "test.txt";
            //use StreamWriter write string into file
            FileStream aFile = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(aFile);
            //StreamWriter sw = new StreamWriter(path, true);
            sw.WriteLine("Hello to you.");
            sw.WriteLine("It is now {0} and things are looking good.", DateTime.Now.ToLongDateString());
            sw.Write("More than that,");
            sw.Write(" it's {0} that C# is fun.", true);
            sw.Close();
            
            //1
            Console.WriteLine("solution 1:--------------------------");
            StreamReader sr = new StreamReader(path);
            string strLine = sr.ReadLine();
            while (strLine != null)
            {
                Console.WriteLine(strLine);
                strLine = sr.ReadLine();
            }
            sr.Close();
            //2
            Console.WriteLine("solution 2:--------------------------");
            sr = new StreamReader(path);
            int nChar;
            nChar = sr.Read();
            while (nChar != -1)
            {
                Console.Write(Convert.ToChar(nChar));
                nChar = sr.Read();
            }
            Console.WriteLine();
            sr.Close();
            //3
            Console.WriteLine("solution 3--------------------------");
            sr = new StreamReader(path);
            strLine = sr.ReadToEnd();
            Console.WriteLine(strLine);
            sr.Close();
            //4
            Console.WriteLine("solution 4--------------------------");
            foreach (string alternativeLine in File.ReadLines(path))
                Console.WriteLine(alternativeLine);

            //read a MapData
            Console.WriteLine("-----------------------------------------------------------");
            List<string> columns;
            List<Dictionary<string, string>> myData = ReadMapData.GetData(out columns);
            foreach (string column in columns)
            {
                Console.Write("{0, -20}", column);
            }
            Console.WriteLine();
            foreach (Dictionary<string, string> row in myData)
            {
                foreach (string column in columns)
                {
                    Console.Write("{0, -20}", row[column]);
                }
                Console.WriteLine();
            }
            Console.WriteLine("-----------------------------------------------------------");

class ReadMapData
    {
        public static List<Dictionary<string, string>> GetData(out List<string> columns)
        {
            string line;
            string[] stringArray;
            char[] charArray = new char[] { ',' };
            List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
            columns = new List<string>();

            try
            {
                FileStream aFile = new FileStream(@"..\..\SomeData.txt", FileMode.Open);
                StreamReader sr = new StreamReader(aFile);

                //Obtain the columns from the first line.
                //Split row of data into string array
                line = sr.ReadLine();
                stringArray = line.Split(charArray);

                for (int x = 0; x <= stringArray.GetUpperBound(0); x++ )
                {
                    columns.Add(stringArray[x]);
                }

                line = sr.ReadLine();
                while (line != null)
                {
                    //Split row of data into string array
                    stringArray = line.Split(charArray);
                    Dictionary<string, string> dataRow = new Dictionary<string, string>();

                    for (int x = 0; x <= stringArray.GetUpperBound(0); x++ )
                    {
                        dataRow.Add(columns[x], stringArray[x]);
                    }
                    data.Add(dataRow);
                    line = sr.ReadLine();
                }
                sr.Close();
                return data;

            }
            catch (System.Exception ex)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
                return data;
            }
        }
    }

三、序列化与反序列化

IFormatter serializer = new BinaryFormatter();

serializer.Serialize(myStream, myObject);

反序列

IFormatter serializer = new BinaryFormatter();

MyObjectType myNewObject = serializer.Deserialize(myStream) as MyObjectType;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值