檔案相關操作

  • 1617
  • 0

摘要:快速簡便的文字讀寫方式



            // 快速簡便的文字讀寫方式
            // 寫檔案
            System.IO.File.WriteAllText(@"a.log", "THIS IS A TEST");
            // 讀檔案
            string s = System.IO.File.ReadAllText(@"a.log");



            //查檔案大小
            System.IO.FileInfo f = new System.IO.FileInfo("C://a.txt");
            MessageBox.Show( f.Length.ToString() );

 


System.IO.Path.GetFileNameWithoutExtension(FileName); //取得無路徑無副檔名的檔案名稱

System.IO.Path.GetDirectoryName(FileName);// 取路徑,沒有最後"/"


        //寫log
        public static void WriteLog(String msg)
        {
            StreamWriter writer = null;
            try
            {
                writer = File.AppendText(@"a.log");
                writer.WriteLine("{0} {1}", DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.fff"), msg);
                writer.Flush();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }