C#寫入文件,與讀取文件內容

/// <summary>
    /// 寫文件
    /// </summary>
    /// <param name="Path">文件路徑</param>
    /// <param name="Name">文件名(包括後綴名)</param>
    /// <param name="content">內容</param>
    /// <returns></returns>
    public static bool WriteFile(string Path, string Name, string content)
    {
        try
        {
            string path = HttpContext.Current.Server.MapPath(Path);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fname = HttpContext.Current.Server.MapPath(Path + "/" + Name);
            if (!File.Exists(fname))
            {
                FileStream fs = File.Create(fname);
                fs.Close();
            }
            StreamWriter sw = new StreamWriter(fname, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.WriteLine(content);
            sw.Close();
            sw.Dispose();
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 讀文件
    /// </summary>
    /// <param name="path">文件路徑</param>
    /// <returns></returns>
    public static string ReadFile(string Path)
    {
        try
        {
            StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(Path), System.Text.Encoding.GetEncoding("utf-8"));
            string content = sr.ReadToEnd().ToString();
            sr.Close();
            return content;
        }
        catch
        {
            return "<span style='color:red; font-size:x-large;'>Sorry,The Ariticle wasn't found!! It may have been deleted accidentally from Server.</span>";
        }
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章