1. 程式人生 > >簡單的讀寫文字

簡單的讀寫文字

 

 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;
            }
        }