简单的读写文本

 private void btnTextWrite_Click()
        {
            //文件路径

            string filePath = @"E:\456.txt";


            try
            {
                //检测文件夹是否存在,不存在则创建
                //string mystr1 = NiceFileProduce.CheckAndCreatPath(NiceFileProduce.DecomposePathAndName(filePath, NiceFileProduce.DecomposePathEnum.PathOnly));

                using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))
                {
                    string  write="kkk";
                    byte[] mybyte = Encoding.UTF8.GetBytes(write);
                    write = Encoding.UTF8.GetString(mybyte);
                    sw.Write(write);
                   // MessageBox.Show("写入数据:"+write);
                }

            }
            catch
            {

            }
         }
            
       private string  btnTexRead_Click()
        {
            //文件路径
            string filePath = @"E:\456.txt";
            string  Text="";
            try
            {
                if (File.Exists(filePath))
                {
                    using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
                    {
                         Text = sr.ReadToEnd();
                        byte[] mybyte = Encoding.UTF8.GetBytes(Text);
                         Text = Encoding.UTF8.GetString(mybyte);
                         //MessageBox.Show("读出的数据:"+Text);
                         return Text;
                    }
                }
                else
                {
                    MessageBox.Show("文件不存在");
                       return Text;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                   return Text;
            }
        }

猜你喜欢

转载自blog.csdn.net/Bamboo265925/article/details/84062983