亲宝软件园·资讯

展开

C#读取写入文件

时间里的 人气:0

最新对文件的操作比较频繁。这里记录一下常用的几种文件读写的方式。

我这里使用窗体来做测试。

1:二进制读写

/// <summary>
        /// 二进制写入文件
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.FileName = "File";
            saveDlg.Title = "保存数据";
            saveDlg.Filter = "File(*.txt)|*.txt";
            saveDlg.DefaultExt = "txt";
            saveDlg.AddExtension = true;
            //saveDlg.InitialDirectory = "D:AMC Results";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                SaveDatafileWithNewVersion(saveDlg.FileName);
                Cursor = Cursors.Default;
            }
        }
  
        /// <summary>
        /// 二进制保存文件
        /// </summary>
        public static void SaveDatafileWithNewVersion(String sFile)
        {
            //文件格式依次为:内部版本号,...
            Stream stream = File.Open(sFile, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(stream);
            bw.Write((Int16)1);//内部版本号,暂时用1,表示版本1,整型
            ///写入Config对象
            bw.Write("泽国江山入战图
");
            bw.Write("生民何计乐樵苏
");
            bw.Write("凭君莫话封侯事
");
            bw.Write("一将功成万骨枯
");
            bw.Close();
            stream.Close();
        }
  
        /// <summary>
        /// 打开文件
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Title = "File";
            openDlg.Filter = "File (*.txt)|*.txt";
  
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                BinaryReader br = new BinaryReader(new FileStream(openDlg.FileName,
                FileMode.Open));
                string str = "";
                int number = br.ReadInt16();
                str += br.ReadString();
                str += br.ReadString();
                str += br.ReadString();
                str += br.ReadString();
  
                richTextBox1.Text = str;
                br.Close();
            }
        }

2:泛型读写:

/// <summary>
        /// 泛型写入
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.FileName = "File";
            saveDlg.Title = "保存数据";
            saveDlg.Filter = "File(*.txt)|*.txt";
            saveDlg.DefaultExt = "txt";
            saveDlg.AddExtension = true;
            //saveDlg.InitialDirectory = "D:AMC Results";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                string str = "泽国江山入战图
生民何计乐樵苏
凭君莫话封侯事
一将功成万骨枯
";
                BinarySerialize<string>(str, saveDlg.FileName);
            }
        }
  
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="obj">写入类型</param>
        /// <param name="path">路径</param>
        public static void BinarySerialize<T>(T obj, string path)
        {
  
            FileStream fileStream = new FileStream(path, FileMode.Create);
            BinaryFormatter b = new BinaryFormatter();
            try
            {
                b.Serialize(fileStream, obj);
                fileStream.Close();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }
  
        /// <summary>
        /// 泛型读取
        /// </summary>
        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Title = "File";
            openDlg.Filter = "File (*.txt)|*.txt";
  
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                string str = BinaryDeserialize<string>(openDlg.FileName);
                richTextBox2.Text = str;
            }
        }
  
        /// <summary>
        /// 读取文件
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static T BinaryDeserialize<T>(string path)
        {
            FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryFormatter b = new BinaryFormatter();    //SoapFormatter
            T rs;
            try
            {
                rs = (T)b.Deserialize(fileStream);
                return rs;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
            return default(T);
        }

3:XML读写:不是很稳定

/// <summary>
        /// XML写入
        /// </summary>
        private void button5_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.FileName = "File";
            saveDlg.Title = "保存数据";
            saveDlg.Filter = "File(*.txt)|*.txt";
            saveDlg.DefaultExt = "txt";
            saveDlg.AddExtension = true;
            //saveDlg.InitialDirectory = "D:AMC Results";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                string str = "泽国江山入战图
生民何计乐樵苏
凭君莫话封侯事
一将功成万骨枯
";
                SerializeToXml<string>(saveDlg.FileName, str);
            }
        }
  
        /// <summary>    
        /// XML序列化某一类型到指定的文件
        /// /// </summary>  
        /// /// <param name="filePath">文件路径</param>  
        /// /// <param name="obj">写入对象</param> 
        /// /// <param name="type"></param>  
        public static void SerializeToXml<T>(string filePath, T obj)
        {
            try
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    xs.Serialize(writer, obj);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
  
        /// <summary>
        /// XML读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Title = "File";
            openDlg.Filter = "File (*.txt)|*.txt";
  
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                string str = DeserializeFromXml<string>(openDlg.FileName);
                richTextBox3.Text = str;
            }
        }
  
        /// <summary>    
        /// 从某一XML文件反序列化到某一类型  
        /// </summary>   
        /// <param name="filePath">待反序列化的XML文件名称</param>
        /// <param name="type">反序列化出的</param> 
        /// <returns></returns>   
        public static T DeserializeFromXml<T>(string filePath)
        {
            try
            {
                if (!System.IO.File.Exists(filePath))
                    throw new ArgumentNullException(filePath + " not Exists");
                using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    T ret = (T)xs.Deserialize(reader);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return default(T);
            }
        }

最终效果:

总结

加载全部内容

相关教程
猜你喜欢
用户评论