C# 讀寫文件操做

因爲代碼比較簡單,就直接貼代碼了。c#

主要用到流的方式進行操做。code

/// <summary>
        /// 寫數據到文件
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="content">內容</param>
        /// <returns>成功 true  失敗 false</returns>
        public static Boolean WriteFile(string path, string content) {
            try
            {
                FileStream fs = new FileStream(path, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                //開始寫入
                sw.Write(content);
                //清空緩衝區
                sw.Flush();
                //關閉流
                sw.Close();
                fs.Close();
                return true;
            }
            catch (Exception e) {
                return false;
            }
            
        }
        /// <summary>  
    /// 讀文件  
    /// </summary>  
    /// <param name="path">文件路徑</param>  
    /// <returns></returns>  
        public static string ReadFile(string Path)
        {
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(Path, System.Text.Encoding.GetEncoding("utf-8"));
                string content = sr.ReadToEnd().ToString();
                sr.Close();
                return content;
            }
            catch
            {
                sr.Close();
                return null;
            }
        }
相關文章
相關標籤/搜索